在 express typescript 应用程序中,通过 next() 传递的错误不会到达错误处理中间件

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() 函数中传递错误时,它不会到达错误处理中间件,结果 html 而不是 json返回给客户端。

我通过在错误处理中间件中添加 next 参数解决了这个问题:

// Error handling
app.use((error: any, req: Request, res: Response, next: NextFunction) => {
  res
    .status(500)
    .json({ 'Server error' });
});

有趣的是,这种行为的原因可能是什么,因为在添加打字稿之前,这个中间件函数在没有这个参数的情况下工作。

错误处理函数是express用来捕获任何错误的一种特殊的中间件,这个中间件必须正好有如下四个参数:

  1. error 是任何错误的实例,或者您可以指定要捕获的错误类型,
  2. 请求对象
  3. 响应对象
  4. 下一个函数,这是必需的,因为您可以根据需要声明任意多个错误处理程序,并且可以继续接下来的流程调用。

所有需要的参数。

// Error handling
// Arbitrary example
app.use((error: any, req: Request, res: Response, next: NextFunction) => 
{
  res
    .status(500)
    .json({ 'Server error' });
});

此外,错误处理程序中间件必须在路由处理程序之后最后声明。