Error handling 快速路线中的错误处理

Error handling 快速路线中的错误处理,error-handling,express,routes,Error Handling,Express,Routes,我有一个包装RESTful API的节点模块。此客户端遵循标准节点回调模式: module.exports = { GetCustomer = function(id, callback) { ...} } 我通过各种快递路线给这位客户打电话,如: app.get('/customer/:customerId', function(req,res) { MyClient.GetCustomer(customerId, function(err,data) { if(err

我有一个包装RESTful API的节点模块。此客户端遵循标准节点回调模式:

module.exports = { 
    GetCustomer = function(id, callback) { ...} 
}
我通过各种快递路线给这位客户打电话,如:

app.get('/customer/:customerId', function(req,res) {
 MyClient.GetCustomer(customerId, function(err,data) {
   if(err === "ConnectionError") {
     res.send(503);
    }
   if(err === "Unauthorized") {
     res.send(401);
    }
    else {
     res.json(200, data);
    }
  };
};
问题是,我认为每次给这个客户打电话时都要检查“ConnectionError”是不容易的。我不相信我可以调用res.next(err),因为这将作为500错误返回


这里是否缺少节点或Javascript模式?在C#或Java中,我会在MyClient中抛出相应的异常。

您想要创建错误处理中间件。以下是Express中的一个示例:

以下是我使用的:

module.exports = function(app) {

  app.use(function(req, res) {
  // curl https://localhost:4000/notfound -vk
  // curl https://localhost:4000/notfound -vkH "Accept: application/json"
    res.status(404);

    if (req.accepts('html')) {
      res.render('error/404', { title:'404: Page not found', error: '404: Page not found', url: req.url });
      return;
    }

    if (req.accepts('json')) {
      res.send({ title: '404: Page not found', error: '404: Page not found', url: req.url });
    }
  });

  app.use( function(err, req, res, next) {
    // curl https://localhost:4000/error/403 -vk
    // curl https://localhost:4000/error/403 -vkH "Accept: application/json"
    var statusCode = err.status || 500;
    var statusText = '';
    var errorDetail = (process.env.NODE_ENV === 'production') ? 'Sorry about this error' : err.stack;

    switch (statusCode) {
    case 400:
      statusText = 'Bad Request';
      break;
    case 401:
      statusText = 'Unauthorized';
      break;
    case 403:
      statusText = 'Forbidden';
      break;
    case 500:
      statusText = 'Internal Server Error';
      break;
    }

    res.status(statusCode);

    if (process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'test') {
      console.log(errorDetail);
    }

    if (req.accepts('html')) {
      res.render('error/500', { title: statusCode + ': ' + statusText, error: errorDetail, url: req.url });
      return;
    }

    if (req.accepts('json')) {
      res.send({ title: statusCode + ': ' + statusText, error: errorDetail, url: req.url });
    }
  });
};

如果您注册了一个自定义的错误处理程序中间件呢?