Search code examples
node.jstypescriptnestjs

Unhandled exception crashes nestjs server


I'm new to Nest.js and building a REST API server. And I'm also using typeorm, which has much async function. If I miss await keyword when I use async function and got an exception like 'QueryFailedError', server emits exception and doesn't work anymore. (all request is rejected, socket hanged up).

If I add code snippet below, server works after exception occurs but function is not working as expected (like transactional event).

process.on('unhandledRejection', (e) => {
  console.log(e);
});

How can I deal with this problem? I want my server wouldn't stop when unhandled exception occurred without loosing functionality. like.. when a problem occurs that is not a matter of nest.js?


Solution

  • This is the default for all node servers. If there's an unhandled exception it will crash the server. As you've noticed, you can use process.on('unhandledRejection') and process.on('unhandledException') to handle the errors. Rather than handling them in global process events, you should be using await or at the very least .catching the promises so that you don't end up with these instances