[英]Express4 error middleware sequence
Came accros a sequence of code execution which I found unusual here is the code: 来了一个代码执行序列,我发现以下代码与众不同:
server.js server.js
const Actions_Single_PVC = require('./routes/Actions_single_PVC.js');
app.use('/Actions_single_PVC', Actions_Single_PVC);
app.use((err, req, res, next) => {
console.log('invalid token');
});
Actions_single_PVC.js Actions_single_PVC.js
router.post('/', asyncMW(async (req, res, next) => {
throw new Error();
}));
router.use((err, req, res, next) => {
console.log('error');
}
And in case you have never seen this construction before here is asyncMW: 如果您之前从未见过这种构造,请参见asyncMW:
const asyncMiddleware = fn =>
(req, res, next) => {
Promise.resolve(fn(req, res, next))
.catch(next);
};
module.exports = asyncMiddleware;
What I didn't understand was that when an error is thrown (I reproduced it here with throw new Error();
) that the error handling middleware in the server.js
file is executed. 我不明白的是,当引发错误时(我在这里用
throw new Error();
再现了该throw new Error();
),执行了server.js
文件中的错误处理中间件。 I expected that the error handling middleware of the Actions_single_PVC.js
would get executed. 我预计将执行
Actions_single_PVC.js
的错误处理中间件。
Why is the error middlware in server.js
executed and not the error middlware in Actions_single_PVC.js
? 为什么执行
server.js
的错误middlware而不执行Actions_single_PVC.js
的错误middlware?
It is because the following code applies middleware to only request with base path matching Actions_single_PVC
. 这是因为以下代码将中间件仅应用于基本路径与
Actions_single_PVC
匹配的请求。
app.use('/Actions_single_PVC', Actions_Single_PVC);
Whereas following code is apply middleware to all global requests. 而以下代码将中间件应用于所有全局请求。
app.use((err, req, res, next) => {
console.log('invalid token');
});
If you'll hit the url /Actions_single_PVC
then the middlewares in Actions_single_PVC
will get hit. 如果你打的网址
/Actions_single_PVC
然后在中间件Actions_single_PVC
会被打到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.