从Express路由引发异常时未调用未处理的异常事件处理程序

时间:2019-06-27 12:28:53

标签: javascript node.js express exception

我编写了一条简单的Express路由来测试我的事件处理程序是否存在未捕获的异常,但是由于某些原因,从路由代码中抛出该事件处理程序时,它并未被调用:

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}...`));

发送GET请求时,我在屏幕上看到以下输出(缩写为更好的可读性的调用堆栈):

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-
...

以下是我的代码的结构(简化版)。异常是从“ routes”文件夹下的代码引发的,应该在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

为什么不调用事件处理程序?

1 个答案:

答案 0 :(得分:1)

请勿使用process.on('uncaughtException', () => {})来捕捉快递中的错误。您可以通过以下方式创建自定义事件处理程序中间件:

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);
}

您可以使用此自定义处理程序

app.use(myCustomErrorHandler);
相关问题