自定义错误和 bluebird 的 catch with ErrorClass 导致无意行为

Custom errors and bluebird's catch with ErrorClass leads to inadvertent behaviour

我正在尝试为自定义错误实现一个模块。

应该可以使用此模块在应用程序的要求声明中实例化单个错误:

var MyCustomError = require('custom-error')('MyCustomError');

这是模块:

'use strict';

var _CACHE = {};

function initError(name) {
  function CustomError(message) {
    this.name = name;
    this.message = message;
  }
  CustomError.prototype = Object.create(Error.prototype);
  CustomError.prototype.constructor = CustomError;
  _CACHE[name] = CustomError;
}

function createCustomError(name) {
  if (!_CACHE[name]) {
    initError(name);
  }
  return _CACHE[name];
}

module.exports = createCustomError;

上面的 require-one-liner 目前有效。

现在,在我的服务中,我想明确地捕获这个错误:

var MyCustomError = require('custom-error')('MyCustomError')
// ...
return fooService.bar()
    .catch(MyCustomError, function (error) {
      logger.warn(error);
      throw error;
    })

如果我在我的测试中通过抛出 MyCustomError 来拒绝 fooService.bar 的承诺,这很好用。

但是,这只有效,因为我的测试和服务正在使用 MyCustomError 的相同实例

例如,如果我在我的自定义错误模块中删除缓存机制,捕获将不会再得到 reached/executed,因为 bluebird 不明白这两个错误是相同的类型:

function createCustomError(name) {
  //if (!_CACHE[name]) {
    initError(name);
  //}
  return _CACHE[name];
}

bluebird处理的具体代码在catch_filter.js,大家可以看看right here.

虽然该方法在我的应用程序中确实有效,但一旦多个模块使用自定义错误模块并且不再共享相同实例,这很快就会导致问题。

如何通过不是比较实例,而是比较错误类型本身来提出这个概念和运行?

干杯,
克里斯托弗

我终于想出了一个稍微不同的方法。对于志同道合的人来说,这是结果:

错误工厂

var
  vsprintf = require("sprintf-js").vsprintf;

function CustomErrorFactory(code, name, httpCode, message) {

  // Bluebird catcher
  this.predicate = function (it) {
    return it.code === code;
  };

  this.new = function (messageParameters, details) {
    return new CustomError(messageParameters, details);
  };

  this.throw = function (messageParameters, details) {
    throw new CustomError(messageParameters, details);
  }; 

  function CustomError(messageParameters, details) {
    this.code = code;
    this.name = name;
    this.message = vsprintf(message, messageParameters);
    this.httpCode = httpCode;
    this.details = details || {};

    // Important: Do not swallow the stacktrace that lead to here.
    // @See 
    Error.captureStackTrace(this, CustomError);
  }

  // CustomError must be instance of the Error-Object
  CustomError.prototype = Object.create(Error.prototype);
  CustomError.prototype.constructor = CustomError;
}

module.exports = CustomErrorFactory;

错误

var
  ErrorFactory = require("./ErrorFactory");

function initErrors() {
  return {
    Parameter: {
      Missing: new ErrorFactory('1x100', 'ParameterMissing', 400, 'Parameter "%s" missing'),
      Invalid: new ErrorFactory('1x200', 'ParameterInvalid', 400, 'Parameter "%s" invalid')
      //..
    },
    Access: {
      NotAccessible: new ErrorFactory('3x100', 'AccessNotAccessible', 403, 'Resource "%s" is not accessible for "%s"'),
      //..
    },
    // ...
    Request: {
      //..
    }
  };
}

module.exports = initErrors();

我创建了一个包含这些的单独模块 类。

然后,在我的实现中,我可以单独捕获这样的错误:

function foo(request, reply) {

  return bluebird
    .resolve(bar)
    .then(reply)

    .catch(Errors.Parameter.Missing.predicate, function () {
      return reply(boom.badRequest());
    })

    .catch(Errors.Entity.NotFound.predicate, function () {
      return reply({}).code(204);
    })

    .catch(Errors.Entity.IllegalState.predicate, function (error) {
      return reply(boom.badImplementation(error.message));
    })

    // any other error
    .catch(function (error) {
      return reply(boom.badImplementation(error.message));
    });
}

投掷

Errors.Entity.IllegalState.throw(['foo', 'bar']);
// or
throw Errors.Entity.IllegalState.new(['foo', 'bar']);

需要

Errors = require('errors'); // all
EntityErors = require('errors').Entity; // one group
EntityNotFoundError = require('errors').Entity.NotFound; // one particular

唯一我仍然不明白的是为什么需要使用谓词函数而不是仅仅将错误对象传递给 catch 子句。但我可以忍受。

你也可以在 catch 中使用谓词函数

function isMyCustomError(f) {
    return f instanceof Error && f.name === "MyCustomError";
}