omer
omer

Reputation: 1440

Unhandled exception event handler not called when exception is thrown from Express routes

I wrote a simple Express route to test my event handler for uncaught exceptions, but for some reason when throwing from the route code, the event handler is not being called:

app.js:

process.on('uncaughtException', err => {
    console.log('Handling exception');
});

app.get('/', (req, res) => {
    console.log('Serving request');
    throw(new Error('Some error'));
    res.send('Hello World!');
});

const port = process.env.PORT || 8888; 
app.listen(port, () => console.log(`Listening on port ${port}...`));

When send a GET request, I see the following output on the screen (call stack abbreviated for better readability):

Listening on port 8888...
Serving request
Error: error
    at app.get (/Users/omerah/Documents/playground/node/hello-server/app.js:48:11)
    at Layer.handle [as handle_request] (/Users/omerah/Documents/playground/node/hello-server/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/omerah/Documents/playground/node/hello-(/Users/omerah/Documents/playground/node/hello-server/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/omerah/Documents/playground/node/hello-
...

Following is the structure of my code (a simplified version). The exceptions are thrown from code under the 'routes' folder and should be catch be the event handler that is defined in app.js:

├── [-rw-r--r--]  app.js
├── [-rw-r--r--]  authenticate.js
├── [drwxr-xr-x]  routes
|   ├── [-rw-r--r--]  login.js
├── [drwxr-xr-x]  modles
├── [drwxr-xr-x]  utils

Why isn't the event handler being called?

Upvotes: 0

Views: 701

Answers (1)

Toby Mellor
Toby Mellor

Reputation: 8205

Don't use process.on('uncaughtException', () => {}) to catch errors in express. You can create a custom event handler middleware through something like:

function myCustomErrorHandler(err, req, res, next) {
  if (<check on error>) {
    console.log('Handling exception');
    // TODO: Optionally, return a response back here using "res"
  }

  next(error);
}

You can use this custom handler

app.use(myCustomErrorHandler);

Upvotes: 1

Related Questions