我有一个错误处理中间件,它可以处理我的 Express 应用程序中的错误,如下所示:
export const errorMiddleware = (app: Application): void => {
// If the route is not correct
app.use(((req, res, next): void => {
const error: any = new Error("Route not found");
error.status = 404;
next(error);
logger.error(`${error.status} ${error.message}`);
}) as RequestHandler);
// If any operation fail and throw error with next will come here
app.use(((error, req, res, next): void => {
logger.error(`${error.status} ${error.message}`);
res.status(error.status || 500).json({
error: {
message: error.message,
},
status: error.status || 500,
});
}) as RequestHandler);
};
第一个 app.use
将错误对象传递给下一个中间件,该中间件在第一个参数中获取该错误对象:
app.use(((error, req, res, next): void => {
现在我已经为其声明了一个 RequestHandler
类型,并且它给出了错误,因为它获取的自定义第一个参数是 error 。
如何使用 RequestHandler 属性并添加一种额外的属性类型来修复此错误?
最佳答案
您不能在这样的回调函数中引入新参数,它只接受固定参数并按顺序排列。因此您的 error
参数将包含 req
!
要将数据从一个中间件传递到下一个中间件,请使用 res.locals
。
看看http://expressjs.com/en/api.html#res.locals
您应该在第一个中间件中设置它,如下所示:
res.locals.error = 'Sorry'
您可以在下一个中间件中使用它,如下所示:
if (res.locals.err) {...}
它会保留在请求的生命周期中。
关于javascript - 如何在express js中间件函数中向RequestHandler声明自定义 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73255579/