2

I have a route

 app.get("/some/url/", function(req, res){ res.sendStatus(404) })

I am trying to handle or catch this 404 in express error handling middleware and it is not working

 app.use(function(err, req, res, next){do something here})

Any help how do i capture the error thrown by route in the middleware.

3
  • The response is still successfully communicated, regardless of the status code, so Express doesn't consider it an error. You can, however, raise an error yourself – res.sendStatus(404); next(new Error('404 Not found'));. Commented Jun 2, 2016 at 5:02
  • 1
    A little more meaningful and less generic title to your question would be good. Commented Jun 2, 2016 at 5:09
  • please add your code snippet... Commented Jun 2, 2016 at 15:28

1 Answer 1

4

app.get("/some/url/", function(req, res) {
    // Generate Error yourself.
    throw new Error("Generated Error.");
});

// global error handler
app.use(function(err, req, res, next) {
    console.dir(err);
    
    if(err) {
        // Your Error Status code and message here.
        res.status(500).send('Something broke!');
    }

    // Send Some valid Response
});

Sign up to request clarification or add additional context in comments.

2 Comments

Just tried your solution, the global error handler was not able to catch the error. It still crashed
Better if you can share the code and detailed issue.

Your Answer

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.