Repository navigation
|
I'm working on a Node.js/Express backend and want to make API error handling consistent across the application. What would be a clean way to structure centralized error handling so that: Different routes can handle errors consistently |
Replies: 1 comment
|
A clean approach is to use Express's centralized error-handling middleware. Each route can either call For example: js file code: class AppError extends Error { |
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;
…