[英]use error middleware when using express.Router
I want to use express.Router in my app. 我想在我的应用中使用express.Router。 I have a file index file that runs the server.
我有一个运行服务器的文件索引文件。 And a file routes that run some express routes, thanks to express.Router.
还有一个文件路由,它运行一些快速路由,这要感谢express.Router。
What I want that, whenever one of my route fails, the error middleware defined in index is reached; 我想要的是,每当我的一条路由发生故障时,都会到达index中定义的错误中间件;
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. 在上面的示例中:-当我使用路由ok时,它起作用-当我使用路由ok时,在未到达错误中间件的情况下引发了错误。
Do you know how to achieve it ? 你知道如何实现吗?
Thank you ! 谢谢 !
https://gist.github.com/VivienAdnot/e3cf44de745531c6cca7be5de53c341a https://gist.github.com/VivienAdnot/e3cf44de745531c6cca7be5de53c341a
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. 查看您的代码,我可以看到您在错误处理程序中间件中缺少'next'参数,因为需要'next'才能将控件传递到下一个匹配的路由。 Just change the middleware code in index.js to,
只需将index.js中的中间件代码更改为
app.use((err, req, res, next) => {
console.log('error mw reached');
res.status(500);
res.end();
next();
});
and it works. 而且有效。
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();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.