Sunday, 12 March 2017

promises - unhandled rejection hangs request

I'm developing a backend app in node.js and I came across with following problem: When developer call promise function like below:

mainRouter.get("/xD", async (req, res) => {
    res.send(await this.fooService.foo());
});

there is possibility that "this.fooService.foo()" function will fail (promise rejection) and the end user will get request timeout.

I want to be sure that developer mistake will not cause UnhandledPromiseRejectionWarning (and finally timeout error). The question is how to configure app to log errors and return status 500 to user when UnhandleRejection occurs.

What I tried:

mainRouter.get("/xD", async (req, res) => {
    try {
        res.send(await this.fooService.foo());
    } catch (err) {
        res.status(500).send("error");
    }
});

Above code will do the thing but it requiers from developer to write above code in every route, so it's not quite a clean solution.

I also tried to use error middleware:

mainRouter.use((err:any, req, res, next) => {
    console.log(err);
    res.status(500).send("Error");
});

but it doesn't catch PromiseRejection

Finally I created middleware which registers function handler for unhandledRecejtion event:

mainRouter.use((req, res, next) => {
    process.on('unhandledRejection', (reason, p) => {
        console.log(reason);
        res.status(500).send("Error");
    });
    next();
});

I'm not sure how process events works in node.js but I'm afraid that the code above will cause problems for scenario:

  1. First request generates unhandled promise rejection
  2. The newest request which registered handler last, will return to user status 500.


via jjusianiec

No comments:

Post a Comment