inversify-express-utils
inversify-express-utils copied to clipboard
Inversify-espress-utils : To handle unhandle error in controller's route handler method
When there is an unhandled error in controller method and if there is a error-handling middleware configured, error-handling middleware can be called with the error.
Expected Behavior
Configured error-handling middleware should be called with unhandled error
Current Behavior
Currently application gets into an unknown state with below error
(node:6264) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Unhandled error
(node:6264) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Possible Solution
Invocation of the handler method can be bought inside a try catch and when a error is caught pass it to next function.
try {
// invoke controller's action
let result = childContainer.getNamed<any>(TYPE.Controller, controllerName)[key](...args);
} catch (error) {
next(error);
}
Steps to Reproduce (for bugs)
> it("should work for unhandled error", (done) => {
> let message = {"message" : "internal error"};
>
> @controller("/")
> class TestController {
> @httpGet("/") public getTest(req: express.Request, res: express.Response) { throw new Error("Unhandled error"); }
> }
>
> server = new InversifyExpressServer(container);
>
> server.setErrorConfig((app: express.Application) => {
> app.use((err: Error, req: express.Request, res: express.Response, nextFunc: express.NextFunction) => {
> res.status(500).send(message);
> });
> });
>
> supertest(server.build())
> .get("/")
> .expect(500, JSON.stringify(message), done);
> });
>
Context
Trying to setup my project with generic error handler which can even catch unhandled errors in my controller's handler methods.
Your Environment
- Version used:
"inversify": "^4.11.1", "inversify-express-utils": "^5.2.1", "reflect-metadata": "^0.1.12", - Environment name and version (e.g. Chrome 39, node.js 5.4): NodeJS - 8.9.4
- Operating System and version (desktop or mobile): Win 8 Desktop
I don't think this applies anymore, it works for me.
I throw from a route, and my error handler kicks in.
Hey, I was having the exact same issue as you!
I fix it by installing the 'express-async-errors' package and importing it in my appplication file