如何使用promise正确处理express.js中的错误(字符串或对象)



我还没有开始我的第一个express.js应用程序,尽管我还需要找出处理错误的最健壮的方法。

由于io.js是几个月前的现实,我正在使用原生Promises来帮助自己实现异步,下面的代码反映了这一点。

我的错误处理中间件如下:

router.use(function (err, req, res, next) {
  // in case err.custom is present, means is an "handled" Error, created by developers
  if (!!err.custom) {
    return res.status(err.code).json(err.message);
  }
  if (err instanceof Error) {
    console.error(err.stack);
    return res.status(500).send('Runtime Error'); // should be reported!
  }
  // last but not least, validation error
  res.status(400).send(err);
});

一个示例控制器是这样写的:

function callService1 (param1) {
  return new Promise(function (resolve, reject) {
    service.call(param1, function (err, data) {
      if (!!err) return reject(err); // this is an Error object?? not sure!
      if (!!data.handledError) { // this is an handled Error to the user, not 500
        return reject({ custom: true, status: 403, message: 'service1 tells you that myCoolParam is not valid' });
      }
      resolve(data);
    });
  };
}
function callService2 (dataFromParam1) {
  return new Promise(function (resolve, reject) {
    // something here
  });
}
// this is the API "controller"
module.exports = function (req, res, next) {
  callService1(req.body.myCoolParam)
  .then(callService2)
  .then(function (service2Output) {
    res.status(200).json({ message: 'everything went smooth!' });
  })
  .catch(next); // here is the catch-all errors
};

正如您所看到的,express中间件看起来相当整洁和优雅
我通常在rejects()中向用户处理所有有趣的错误,其中一些错误是用一个对象调用的,我告诉错误处理中间件。

问题是示例中的service是第三方库。这些库有时返回字符串,有时返回对象(来自外部API),有时返回javascript错误。

目前我无法处理自定义的javascript对象,此外,如果我想向用户抛出错误500,我必须执行reject(new Error(err));,但有时这个err是一个对象,导致:

Error: [object Object]
    at errorHandler (awesomeapipostsomething.js:123:16)
    at IncomingMessage.<anonymous> (node_modulesmandrill-apimandrill.js:83:24)
    at emitNone (events.js:72:20)
    at IncomingMessage.emit (events.js:163:7)
    at _stream_readable.js:891:16
    at process._tickCallback (node.js:337:11)

这一点都不酷,我真的很想找到一种方法来优雅地处理这些错误,而不添加代码(如果可能的话),因为我发现这种语法非常优雅和简洁。

我对这个问题想了很多,最终创建/使用了https://github.com/yzarubin/x-error/blob/master/lib/x-error.js它是一个自定义的服务器端错误对象,继承了error,并扩展了处理http代码和响应的功能。

为了将其应用于您的情况,我会做一些类似的事情:

function callService1 (param1) {
  return new Promise(function (resolve, reject) {
    service.call(param1, function (err, data) {
      if (!!err) return reject(new xError().extend(err).setHttpCode(500)); // This will inherit the original stack & message
      if (!!data.handledError) { 
        return reject(new xError('this is an handled Error to the user, not 500').setHttpCode(403));
      }
      resolve(data);
    });
  };
}

然后在您的控制器中,您可以检查instanceofxError===true并处理它,或者执行某种默认响应。但我也在一个应用程序中做过这样的事情,在这个应用程序中,每个承诺最终都会解决或拒绝xError:的实例

router.use(function (err, req, res, next) {
  res.status(err.httpCode || 500).send(err.message || 'Internal error');
});

相关内容

最新更新