用户代码异常上的Acitvate express/节点错误处理程序



我有如下代码:

app.js

app.use(app.router)
app.use(function(err, req, res, next) {
  res.render(errorPage)
})
app.get('/', function(req,res,next) {
  module1.throwException(function{ ... });
});

模块1.js

exports.thowException = function(callback) {
       // this throws a TypeError exception.
       // follwoing two lines are getting executed async
       // for simplicity I removed the async code
       var myVar = undefined;
       myVar['a'] = 'b'
       callback()
}

除了module1.js中的异常,我的节点prcoess将终止。相反,我想呈现错误页面。

我试着试着。。。在应用程序中捕获。get(..),它没有帮助。

我该怎么做??

不能将try ... catch与异步代码一起使用。在这篇文章中,你可以在node.js中找到一些错误处理的基本原则。在这种情况下,你应该从模块中返回error作为回调的第一个参数,而不是抛出它,然后再调用错误处理程序。因为您的错误处理函数就在app.route处理程序之后,所以如果您的任何路由不匹配,您也应该检查Not Found错误。下面的代码是一个非常简单的例子。

app.js

app.use(app.router)
app.use(function(err, req, res, next) {
  if (err) {
    res.render(errorPage); // handle some internal error
  } else {
    res.render(error404Page); // handle Not Found error
  }
})
app.get('/', function(req, res, next) {
  module1.notThrowException(function(err, result) {
    if (err) {
      next(new Error('Some internal error'));
    }
    // send some response to user here
  });
});

模块1.js

exports.notThrowException = function(callback) {
  var myVar = undefined;
  try {
    myVar['a'] = 'b';
  } catch(err) {
    callback(err)
  }
  // do some other calculations here 
  callback(null, result); // report result for success
}

最新更新