JavaScript中创建自定义错误的正确方式

4

如何正确定义JavaScript中的自定义错误?

在搜索SO时,我找到了大约6种不同的定义自定义错误的方法,但是我不确定每种方法的(缺)点。

从我(有限的)理解JavaScript中的原型继承来看,此代码应该足够:

function CustomError(message) {
   this.name = "CustomError";
   this.message = message;
}
CustomError.prototype = Object.create(Error.prototype);

在这里有一些相关的内容:https://dev59.com/C3RA5IYBdhLWcg3w6SXZ - Netorica
这是我困惑的主要SO问题。排名最高的答案列出了两种不同的方式,用于自定义错误从“Error”对象继承,其中没有使用“Object.create()”方法。其他答案似乎是这个主题的变体。 - n0w
1
Object.create仅仅是一种新的实现方式,用于替代CustomError.prototype = new Error()。-- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create - James Sumners
1
@n0w 相关:使用Object.create进行继承的好处 - Jonathan Lonowski
请参见https://dev59.com/KXM_5IYBdhLWcg3wcCnc。 - Matt Browne
4个回答

4

当然,最简单且在我看来最好的方法(除非你需要更复杂的错误报告/处理)是:

throw Error("ERROR: This is an error, do not be alarmed.")

2
通常我只使用throw new Error(...),但对于自定义错误,我发现以下代码非常有效,并且在V8上仍然提供堆栈跟踪,在Chrome和node.js中(如果您只是调用Error.apply(),则无法得到这些信息):
function CustomError(message) {
    // Creates the this.stack getter
    if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor)
    this.message = message;
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.constructor = CustomError;
CustomError.prototype.name = 'CustomError';

更多信息请参见以下链接:

JavaScript中扩展Error的好方法是什么?

https://plus.google.com/+MalteUbl/posts/HPA9uYimrQg


谢谢。这似乎可以正确地工作,同时在可用的情况下定义了this.stack。我自己代码中唯一的更改是在构造函数中也定义this.name - n0w
好的建议;我已经加入了(在原型上完成,因为名称对于所有实例都是相同的,但这并不重要)。 - Matt Browne
注意:为了与IE更兼容,还需要一些其他的东西;请参见https://dev59.com/KXM_5IYBdhLWcg3wcCnc#8460753。 - Matt Browne

1
这个脚本描述了在JavaScript中创建和使用自定义错误的所有可能机制。
此外,要完全理解,必须了解JavaScript中的原型继承和委派。我写了一篇文章,清晰地解释了这一点。https://medium.com/@amarpreet.singh/javascript-and-inheritance-90672f53d53c 希望这能帮到你。
function add(x, y) {
      if (x && y) {
        return x + y;
      } else {
        /**
         * 
         * the error thrown will be instanceof Error class and InvalidArgsError also
         */
        throw new InvalidArgsError();
        // throw new Invalid_Args_Error(); 
      }
    }

    // Declare custom error using using Class
    class Invalid_Args_Error extends Error {
      constructor() {
        super("Invalid arguments");
        Error.captureStackTrace(this);
      }
    }

    // Declare custom error using Function
    function InvalidArgsError(message) {
      this.message = `Invalid arguments`;
      Error.captureStackTrace(this);
    }
    // does the same magic as extends keyword
    Object.setPrototypeOf(InvalidArgsError.prototype, Error.prototype);

    try{
      add(2)
    }catch(e){
      // true
      if(e instanceof Error){
        console.log(e)
      }
      // true
      if(e instanceof InvalidArgsError){
        console.log(e)
      }
    }

0
function CustomError() {
   var returned = Error.apply(this, arguments);
   this.name = "CustomError";
   this.message = returned.message;
}
CustomError.prototype = Object.create(Error.prototype);
//CustomError.prototype = new Error();

var nie = new CustomError("some message");

console.log(nie);
console.log(nie.name);
console.log(nie.message);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接