Node.js Error Handling with await-to-js

Most developers write try/catch in every single async function. There's a better way. I discovered the await-to-js pattern a while back, and it completely changed how I handle errors in Node.js and TypeScript. Instead of this mess: try { ... } catch(e) { console.log("error") } try { ... } catch(e) { console.log("error") } try { ... } catch(e) { console.log("error") } You write one tiny helper once, and every async call returns a clean [error, data] tuple. No nesting. No swallowed errors. No repeated boilerplate. The library is literally called await-to-js (npm). It has 3.5k stars. 400 bytes. Life-changing. If you're building any Node.js, Next.js, or backend API, add this to your utils file today. You'll wonder how you coded without it. 💬 Drop a comment if you use a different error handling pattern — always curious what others do. #JavaScript #NodeJS #CleanCode #WebDev #Programming #SoftwareEngineering #100DaysOfCode

  • text

The actual utility function (save this): export const to = (promise) => promise.then(data => [null, data]).catch(err => [err, null]); Add this to your utils.js and import it anywhere. That's it. No npm needed.

This pattern is essentially the Go-style [error, value] return, which Go has used for years. In practice, it often becomes quite verbose. One issue in TypeScript is that neither the transpiler nor most LSPs reliably warn about unused tuple values, so it's easy to accidentally ignore the error. It also makes error propagation more cumbersome, because every function in the call chain needs to explicitly return the error instead of letting it bubble up naturally like exceptions do. In larger codebases, this can actually make error handling harder to reason about rather than simpler.

Using a lib that's a simple try catch/Promise.resolve and Promise.reject underneath to mimic "controversial" go style error handling is the most js community thing, the js community has done in a while

that's quite go-ish style programming in typescript. Not sure if its a good idea for large codebases in terms of readability

Not a good idea for a really large codebase. You need to know where issues spur from. try{}catch(err){} is a good reducnacy in my opinion.

See more comments

To view or add a comment, sign in

Explore content categories