I'm stuck on how to design error handling in an Express.js application. What are the best design practices to handle errors in Express?
To my understanding, I can handle errors in 2 different ways:
First way would be to use an error middleware and, when an error is thrown in a route, propagate the error to that error middleware. This means that we have to insert the logic of the error handler in the middleware itself (note, the middleware here was purposely kept simple).
app.post('/someapi', (req, res, next) => {
if(req.params.id == undefined) {
let err = new Error('ID is not defined');
return next(err);
}
// do something otherwise
});
app.use((err, req, res, next)=>{
// some error logic
res.status(err.status || 500).send(err);
});
Another option is to deal with the errors on the spot, when the error happens. This means that the logic must be in the route itself
app.post('/someapi', (req, res, next) => {
if(req.params.id == undefined) {
let err = new Error('ID is not defined');
// possibly add some logic
return res.status(ErrorCode).send(err.message);
}
// do something otherwise
});
What is the best approach, and what are the best design practices for this?
Thank you
Aucun commentaire:
Enregistrer un commentaire