0

我看到了一个非常特殊(也很奇怪)的错误处理代码,如下所示:

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

1 回答 1

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 {}

它基本上只是创建一个什么都不做的子类。

于 2018-07-30T15:48:52.123 回答