1

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
asked Oct 16, 2019 at 6:32
0

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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 });
})
answered Oct 16, 2019 at 7:32

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.