繁体   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