【问题标题】:In express typescript app, error passed with next() does not get to error handling middleware在 express typescript 应用程序中,通过 next() 传递的错误不会到达错误处理中间件
【发布时间】:2022-01-27 00:09:39
【问题描述】:

这是有问题的代码:

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 返回给客户端。

【问题讨论】:

    标签: typescript express error-handling middleware


    【解决方案1】:

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

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

    所有for参数根据需要。

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

    错误处理程序中间件也必须在路由处理程序之后声明。

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-10-06
        • 1970-01-01
        • 2021-04-14
        • 2021-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多