async/await Error Handling in JavaScript: try/catch Patterns That Don't Hide Bugs (video)

How to handle errors with async/await in JavaScript and TypeScript: try/catch done right, empty catch blocks, unhandled promise rejections, Promise.allSettled, finally, and where to handle errors centrally.

Read the full article

Transcript

async/await Error Handling in JavaScript: try/catch Patterns That Don't Hide Bugs. Here's the short version.

async/await makes asynchronous JavaScript read like normal code, and try/catch works with it. But a missing await, an empty catch, or a forgotten rejection can still make errors vanish or crash a Node.js process.

Pitfall 2: a missing await. try/catch only catches a rejection if the promise is awaited inside the try. Returning or calling a promise without await lets the rejection escape the catch.

Here's an example: The save fails and nobody finds out.

Pitfall 3: unhandled promise rejections. Since Node.js 15, an unhandled promise rejection crashes the process by default. Fire-and-forget calls are the usual cause.

Running several tasks: all vs allSettled. Promise.all rejects as soon as one promise rejects. Use it when every result is required. Promise.allSettled waits for all of them and tells you which failed. Use it when partial success is fine.

Want to find these issues in your own code? Connect your GitHub repository to CodeInspector. You'll get findings with the file, line, severity, and a recommended fix, plus HTML and PDF reports for your team. Start free at codeinspector.app.

More videos

All videos