Skip to content
Discussion options

You must be logged in to vote

A clean approach is to use Express's centralized error-handling middleware.

Each route can either call next(error) or throw an error from an async handler, and one middleware at the end of the middleware chain can handle the response consistently.

For example:

js file code:

class AppError extends Error {
constructor(message, statusCode) {
super(message);
this.statusCode = statusCode;
}
}
app.get("/users/:id", async (req, res, next) => {
try {
const user = await getUser(req.params.id);
if (!user) {
throw new AppError("User not found", 404);
}
res.json(user);
} catch (error) {
next(error);
}
});
app.use((err, req, res, next) => {
console.error(err);
const statusCode = err.statusCode || 500;
…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by 4kash7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants