0

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

1

2 Answers 2

1

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.

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

Comments

0

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();
});

Comments

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.