Recover from Uncaught Exception in Node.JS

房东的猫 提交于 2019-11-27 21:16:09
thejh

When an uncaught exception occurs, you're in an unclean state. Let the process die and restart it, there's nothing else you can do to safely bring it back to a known-good state. Use forever, it'll restart your process as soon as it dies.

If error is thrown synchronously, express won't stop working, only returning 500.

this.app.get("/error", (request, response) => {
  throw new Error("shouldn't stop");
});

If error is thrown asynchronously, express will crash. But according to it's official documentation, there is still a way to recover from it by calling next:

this.app.get("/error", (request, response, next) => {
  setTimeout(() => {
    try {
      throw new Error("shouldn't stop");
    } catch (err) {
      next(err);
    }
  }, 0);
});

This will let express do its duty to response with a 500 error.

Use try/catch/finally.

app.get('/hang', function(req, res, next) {
    console.log("In /hang route");
    setTimeout(function() {
        console.log("In /hang callback");
        try {
            if(reqNum >= 3)
                throw new Error("Problem occurred");
        } catch (err) {
            console.log("There was an error", err);
        } finally {
            res.send("It worked!");
        }
    }, 2000);
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!