6 ms·
> Because in JavaScript, if something goes wrong, we just throw! A bit out of topic: somewhat ironic that the JS/TS-based projects in my workplace we ended up
by valand 5y ago
> Because in JavaScript, if something goes wrong, we just throw!
A bit out of topic: somewhat ironic that the JS/TS-based projects in my workplace we ended up using return and Result<T, E>-like struct, backed by TypeScript's union type.
Throws is only for never-scenarios and unhandled cases.
Rust-like approach has been very successful to squash runtime bugs, especially in big, complex products.
- rattray 5y agoI 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.