简体   繁体   English

无法从 inversify-express-utils 控制器全局捕获错误

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

I'm using this package https://github.com/inversify/inversify-express-utils for a nodejs app, and I want to have a place to handle errors from any controller, the way I know is to use express error handler , but it doesn't seems to work in this case- nobody calls the error handler:我正在将这个包https://github.com/inversify/inversify-express-utils用于 nodejs 应用程序,我想有一个地方来处理来自任何控制器的错误,我知道的方法是使用快速错误处理程序,但在这种情况下似乎不起作用 - 没有人调用错误处理程序:

userController.ts用户控制器.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!');
    }
}

server.ts服务器.ts

....

const server = new InversifyExpressServer(container);

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

    return app;
});
  1. Why the handler not being called?为什么不调用处理程序?
  2. There is a more elegant way to do this using the inversify-express package?使用 inversify-express 包有更优雅的方法来做到这一点吗?

You should use setErrorConfig when init a server, like this:您应该在初始化服务器时使用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