簡體   English   中英

無法從 inversify-express-utils 控制器全局捕獲錯誤

[英]Unable to catch errors globally from inversify-express-utils controllers

我正在將這個包https://github.com/inversify/inversify-express-utils用於 nodejs 應用程序,我想有一個地方來處理來自任何控制器的錯誤,我知道的方法是使用快速錯誤處理程序,但在這種情況下似乎不起作用 - 沒有人調用錯誤處理程序:

用戶控制器.ts

import {interfaces, controller, request, response, httpGet} from "inversify-express-utils";

@controller('/user')
class UserController implements interfaces.Controller {
    
    ....

    @httpGet('/')
    private async get(@request() req, @response() res) {
        throw new Error('BROKEN!');
    }
}

服務器.ts

....

const server = new InversifyExpressServer(container);

server.setConfig((app) => {
    ...
    
    app.use((err, req, res, next) => {
        console.log(err); // This never called
    });

    return app;
});
  1. 為什么不調用處理程序?
  2. 使用 inversify-express 包有更優雅的方法來做到這一點嗎?

您應該在初始化服務器時使用setErrorConfig ,如下所示:

server.setErrorConfig((app) => {
  app.use((err, req, res, next) => {
    if (err) {
      if (err instanceof HttpRedirectError) {
        return res.redirect(err.redirectUrl);
      }
      return res.json(Requester.createError(err));
    }
    next();
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM