Pavan Kumar
Pavan Kumar

Reputation: 1891

Node js event loop Exception handling

This is query regarding how exception is handled in node js.

Let's say there is an node + express web server. As we know it handles multiple requests in single thread - serves one request while other is waiting for IO.

Let's say while processing a request an exception will occur which is unhandled.

  1. In above scenario, won't pending requests will be thrown away because of crash?
  2. If yes, Is there well defined mechanism to overcome this?

Upvotes: 1

Views: 1179

Answers (1)

Eugene
Eugene

Reputation: 186

  1. Yep
  2. You could listen such errors on process and avoid crashes:

    process.on('unhandledRejection', (reason, promise) => { console.log(reason + "--" + promise); });

    process.on('uncaughtException', (err) => { console.error("uncaught exception:" + err + "\n" + err.stack); });

    process.on('error',(err)=>{ console.log('caught in app error listener: ' + err); });

Please note, it is not a best practice to override such listeners coz you may face with unpredictable behavior in your code. You should always handle errors in your local methods (handle error callback, check correct type, use try...catch, use .catch etc...)

Upvotes: 1

Related Questions