Search code examples
node.jsexpressinversifyjs

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:

userController.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

....

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?

Solution

  • You should use setErrorConfig when init a server, like this:

    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();
      });
    });