带有错误原型的抛出错误和抛出函数之间有什么区别

时间:2018-07-30 15:23:29

标签: javascript ecmascript-6 es6-promise

我看到了一个非常特殊的(奇怪的)错误处理代码,它像这样:

function SomeError(name, message) {
    this.name = name;
    this.message = message;
    this.stack = (new Error()).stack;
}
SomeError.prototype = Object.create(Error.prototype);

承诺承诺:

promise.catch(e => {
    throw new SomeError('someName', e.message);
});

我的问题:
有没有合理的理由这样做?
我想像这样处理:

promise.catch(e => {
    e.name = 'my error name';
    throw new Error(e);
});

1 个答案:

答案 0 :(得分:0)

因为它使您可以细化捕获的食物:

 // Somewhere up the promise chain:
 .catch(error => {
    if(error instanceof SomeError) {
      // Handle this specific case
    } else { /* handle other cases */}
  });

定义SomeError的代码可以重写为以下类,以清楚说明其作用:

 class SomeError extends Error {}

它基本上只是创建一个不执行任何操作的子类。