首页 > 解决方案 > 节点 | 错误中间件不处理异常

问题描述

我们的后端应用是基于node和TS的,我们使用了nightJS库。不幸的是,当我尝试创建和错误中间件时,同时使用:

 this.app.use((error:Error, req: Request, res: Response, next: NextFunction) => {
        console.log("error captured ");
        next(error);
    });

或者:

@ClassErrorMiddleware(logErrorAndStop)

但是当我在控制器中抛出错误时:

@Get("table")
private async getAssetsForTable(req: UserRequest, res: Response) {
    throw Error("table error");
}

我预计该错误将在其中一个中间件中被捕获,但线程却堆积在错误上:

2021-03-14T15:09:20.060Z error: unhandled error Error: table error

并且服务器不返回任何响应(客户端正在等待,可能直到超时)。

我也尝试过这样的事情:

 this.app.use((req: Request, res: Response, next: NextFunction) => {
        try {
            console.log("middleware test");
            next();
        }catch (ex){
            next(ex);
        }

    });

为每个请求打印了“中间件测试”字符串,但随后线程仍然如前所述被卡住。

任何想法为什么?

标签: node.jstypescript

解决方案


快速中间件不处理未处理的拒绝。

例如

import express from 'express'

const app = express();

app.use(someBeforeHookMiddleware) // Middleware that are called before entering into the routes

app.get('/test1', (req, res, next) => {
  throw new Error('Hello Unhandled') // This kind of error are Unhandled and can't be caught by Express Middleware
});

app.get('/test2', (req, res, next) => {
  try {
    const raiseSomeError = someErrorCausingFunction();

    if(!raiseSomeError) next() // if no error in the above function simply pass to next handler without args to next()
  } catch(error) {
    next(error) // passing error here so Error middleware is activated in the chain
  }
});


// Error handling middleware
app.use((err, req, res, next) => {
 console.log('Oops !!, Error occured in req->res cycle ', error.message);
 res.status(err.status).json({ error }); // Send back Error to the Frontend
})


推荐阅读