I have several mongoose route api functions and I would like to know what is the best approach in error handling. Below is an example function. In the first part, I am doing some mongoose database querying, then I execute async function with exec, then I catch any errors, else I am processing data further.
exports.getStornoData = function(req,res,next) {
Produkt.aggregate([
{
"$unwind":"$DemonstratorWerte"
},
{
$match: {
"DemonstratorWerte.Demonstrator":+req.params.demo_id, "DemonstratorWerte.RstorniertDemo.B":true
}
},...
]).exec(function(err, result) {
if (err) {
next(err);
res.status('404').send();
}
else {
//process data...
res.locals.stornierungen = stornierungenArray;
next();
}
})
}
Is that error handling approach acceptable? How can I catch most errors and output (or collect) them on a place where it does not disturb user experience?
if (err) {
next(err);
res.status('404').send();
}
and is this correct with next(err) and sending the status of 404 with method chaining thereafter?
See the express error handling documentation .
Instead of returning a 404 in your own middleware functions, you should define your own "custom" error handling middleware:
function errorHandler (err, req, res, next) {
// Decide what to return to client here based on type of error.
}
Make sure to define error-handling middleware last, after other app.use() and routes calls.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.