Vivien Adnot
Vivien Adnot

Reputation: 1257

use error middleware when using express.Router

I want to use express.Router in my app. I have a file index file that runs the server. And a file routes that run some express routes, thanks to express.Router.

What I want that, whenever one of my route fails, the error middleware defined in index is reached;

In the example above: - when I use the route ok, it works - when I use the route no ok, the error is thrown without reaching the error middleware.

Do you know how to achieve it ?

Thank you !

https://gist.github.com/VivienAdnot/e3cf44de745531c6cca7be5de53c341a

Upvotes: 0

Views: 362

Answers (2)

Narendra Kamath
Narendra Kamath

Reputation: 59

Looking at your code, I can see that you are missing the 'next' argument in the error-handler middleware, since 'next' is required to pass the control to the next matching route. Just change the middleware code in index.js to,

app.use((err, req, res, next) => {
    console.log('error mw reached');
    res.status(500);
    res.end();
    next();
});

and it works.

Upvotes: 1

Vivien Adnot
Vivien Adnot

Reputation: 1257

My error middleware was bad-named ...

// doesn't work
app.use((err, req, res) => {
    console.log('error mw reached');
    res.status(500);
    res.end();
});

to:

//works
app.use((err, req, res, next) => {
    console.log('error mw reached');
    res.status(500);
    res.end();
});

Upvotes: 0

Related Questions