[英]In express typescript app, error passed with next() does not get to error handling middleware
这是有问题的代码:
import express from 'express';
// Non existing routes
app.use((req: Request, res: Response, next: NextFunction) => {
return next(new Error('Test error));
});
// Error handling
// Arbitrary example
app.use((error: any, req: Request, res: Response) => {
res
.status(500)
.json({ 'Server error' });
});
问题是,例如,当在缺少路由中间件的next()
function 中传递错误时,它不会到达错误处理中间件,结果 html 而不是 Z466DEEC76ECDF5FCA6548571F632 返回给客户端。
我能够通过在错误处理中间件中添加next
参数来解决这个问题:
// Error handling
app.use((error: any, req: Request, res: Response, next: NextFunction) => {
res
.status(500)
.json({ 'Server error' });
});
有趣的是,这种行为的原因可能是什么,因为在添加 typescript 之前,这个中间件 function 在没有这个参数的情况下工作。
错误处理程序 function 是一种特殊的中间件,用于快速捕获任何错误,该中间件必须具有以下四个参数:
所有的for参数根据需要。
// Error handling
// Arbitrary example
app.use((error: any, req: Request, res: Response, next: NextFunction) =>
{
res
.status(500)
.json({ 'Server error' });
});
此外,错误处理程序中间件必须在路由处理程序之后的末尾声明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.