0

I have a simple web application using koa and would like to crash the process when an error occurs that I was not expecting. Unfortunately koa seems to always catch the error, report it to stderr and keeps the process running. Is there a way to override this behaviour?

I have reviewed Does Koa safely handle errors? and it mentions 2 scenarios that koa will not trap, but it states that the first one is malformed and I cannot quite figure out how to use the second one.

For reference I have the following error handler which tries to report the failure to the user with a unique'ish id and then crash using the setImmediate method:

app.use(function* (next) {
    try {
        yield next;
    } catch (err) {
        // https://stackoverflow.com/questions/10985872/nodejs-generate-short-unique-alphanumeric
        var tuple = this.request.socket.remoteAddress + ":" + this.request.socket.remotePort;
        var errorSession = parseInt(tuple.replace(/[^\d]/g, ''), 10).toString(36).toUpperCase();
        err.message = "["+errorSession+"] "+err.message;
        logger.error(err);
        this.status = err.status || 500;
        yield this.render('unknown-error', { errorSession : errorSession });

        // this kinda works, but is considered malformed
        setImmediate(function () { throw err;});
    }
});
Community
  • 1
  • 1
GeekyDeaks
  • 650
  • 6
  • 12
  • What about exiting the process on the response's "finish" event, to be sure that you're crashing after sending it? `this.body = 42; this.res.on('finish', () => process.exit(1))` – danneu Oct 12 '16 at 23:54
  • Ah that's a good point @danneu. I had assumed the yield would wait until the response had been sent, but confess that I have not tested this very comprehensively. I'll take a look at the code to check it's really doing that. – GeekyDeaks Oct 13 '16 at 08:23
  • you yield `this.render` because it may need to do async I/O things like read a template from the filesystem. the response doesn't get flushed until the middleware/handler chain have finished and koa is back in control (https://github.com/koajs/koa/blob/2600a20eca77349f4fbd21126cb67d857f540cda/lib/application.js#L132-L139). What are you trying to do? – danneu Oct 13 '16 at 17:10
  • Hi @danneu - I was just trying to crash and let pm2 restart the app when an unexpected error occurred. Thanks for the link and I understand what you mean about waiting to flush the response - I was hoping to figure out if the promise from render() was resolved on either the 'end' or 'finish' event for that reason and not got around to it yet, but I think you may just have answered my question anyway. – GeekyDeaks Oct 15 '16 at 10:38

0 Answers0