1. 程式人生 > >nodejs中處理回撥函式的異常

nodejs中處理回撥函式的異常

如果是使用nodejs+express3這個經典的組合,那麼有一種很方面的處理回撥函式異常的方法:

1. 安裝模組:express-domain-middleware

2. 加入如下的程式碼:

app.use(require('express-domain-middleware'));
app.use(function errorHandler(err, req, res, next) {
  logger.error('error on request %d %s %s: %j', process.domain.id, req.method, req.url, err);
  res.send(500, "there is an error in callback function");
  if(err.domain) {
    //you should think about gracefully stopping & respawning your server
    //since an unhandled error might put your application into an unknown state
  }
});
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));