Facebook Pixel

Why use a custom ApiError class with asyncHandler?

ApiError carries a status and message, so the error handler can return the right status code and a safe message. Combined with asyncHandler, async handlers read cleanly: throw new ApiError(404, 'User not found') and the rest is handled.

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Async Error Handling in Express: Best Practices

Wrap async handlers with asyncHandler: Promise.resolve(fn(req, res, next)).catch(next). The wrapper catches promise rejections and passes them to the error handler. Then you can throw inside async handlers.

Express 4 was designed before async/await. It does not catch promise rejections from async handlers. The handler returns a rejected promise that Express ignores, and the client hangs.

Yes. Express 5 catches promise rejections from async handlers and passes them to the error handler. The asyncHandler wrapper is still useful for older versions.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.