Search code examples
node.jswinstonhapi

Logging all unhandled exceptions in HAPI with Winston


I'm using Winston to log to file / seq information I specifically log using log.info or some other level. But I've noticed that when an unhandled exception occurs, it's not logged... I'm not really familiar with Nodejs and HAPI (need to perform some activity while my colleagues are on vacation).. but I was wondering if there's a sort of middleware where I can attach and let Winston log all HAPI stuff.

Thanks in advance


Solution

  • You can listen on uncaughtException and/or unhandledRejection of your current Node.js process to call you logger (here I simply called console.log):

    process.on('uncaughtException', (err, origin) => {
      console.log('Caught exception:', err, 'Exception origin:', origin);
    });
    
    process.on('unhandledRejection', (reason, promise) => {
      console.log('Unhandled Rejection at:', promise, 'reason:', reason);
    });
    

    However:

    uncaughtException is a crude mechanism for exception handling intended to be used only as a last resort.

    ...

    The correct use of uncaughtException is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting down the process. It is not safe to resume normal operation after uncaughtException.

    Read also Catch all uncaughtException for Node js app.