【问题标题】:Error handling in an Express routeExpress 路由中的错误处理
【发布时间】:2013-10-18 21:10:23
【问题描述】:

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

module.exports = { 
    GetCustomer = function(id, callback) { ...} 
}

我从各种 Express 路由中呼叫该客户,如下所示:

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”并不是 DRY。我不相信我可以打电话给res.next(err),因为这会作为 500 错误返回。

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

【问题讨论】:

  • 如果注册自定义错误处理程序中间件会怎样?

标签: error-handling express routes


【解决方案1】:

您想创建错误处理中间件。这是 Express 的一个示例:https://github.com/visionmedia/express/blob/master/examples/error-pages/index.js

这是我使用的:

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

【讨论】:

    猜你喜欢
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多