How to catch the error which is throwing in middleware function in router(/test) method
app.use(function(err, req, res, next) {
throw new Error('test');
next("its failing")
})
app.get('/test',function(req,res,error){
res.send({ message: error.message });
})
Eslam Abu Hugair
1,2101 gold badge12 silver badges24 bronze badges
2 Answers 2
You can pass variables from your middleware to route handlers using the res.locals object. If you pass the error object you can check for this in your route handler.
app.use(function(req, res, next) {
try {
throw new Error('test error');
} catch (err) {
res.locals.Error = err;
}
next();
})
app.get('/test', function(req,res,error){
if (res.locals.Error) {
res.status(500).json({ message: res.locals.Error.message})
} else {
res.send("OK");
}
})
Note: You can also pass an error directly to the next() function. Express will skip any remaining handlers if you do this however. See Express error handling
For example:
app.use(function(req, res, next) {
try {
throw new Error('test error');
} catch (err) {
next(err);
}
})
answered Oct 16, 2019 at 6:58
Terry Lennox
30.9k5 gold badges37 silver badges45 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Below snippet is working as expected
var a=function test(req,res,next){
try {
throw new Error('test error');
} catch (err) {
next(err);
}
}
app.get('/test',a, function(req,res){
res.send(200)
}, (err, req, res, next) => {
res.status(400).send({ error: err.message });
})
Comments
lang-js