4 ms·
I really like this pattern in TS: const x: Data | Error = await fetchData().catch(e => e); if (x instanceof Error) { return 'too bad' } /
by rattray 6y ago
I really like this pattern in TS:
const x: Data | Error = await fetchData().catch(e => e);
if (x instanceof Error) {
return 'too bad'
}
// proceed with x as Data
Basically you add `.catch(e => e)` to any I/O which may fail, and handle the error in an `if` instead of a `try`.
Many of the benefits of Go's error handling, but without the awkward extra variable and without a chance of using your result without ensuring it isn't an error.