简体   繁体   English

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

[英]Correct way to create custom errors in javascript

What is the correct way to define a custom error in JavaScript? 在JavaScript中定义自定义错误的正确方法是什么?

Searching through SO I've found about 6 different ways to define a custom error, but I'm unsure as to the (dis)advantages to each of them. 通过搜索SO,我发现了大约6种不同的方式来定义自定义错误,但是我不确定每种方式的(缺点)优势。

From my (limited) understanding of prototype inheritance in JavaScript, this code should be sufficient: 从我对JavaScript原型继承的(有限的)理解中,这段代码应该足够了:

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

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

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

Usually I just use throw new Error(...) , but for custom errors I find the following code works pretty well and still gives you stack traces on V8, ie in Chrome and node.js (which you don't get just by calling Error.apply() as suggested in the other answer): 通常,我只使用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';

For more info, see these links: 有关更多信息,请参见以下链接:

What's a good way to extend Error in JavaScript? 在JavaScript中扩展Error的好方法是什么?

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

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

This script depicts all the possible mechanisms for creating and using custom errors in JavaScript. 该脚本描述了在JavaScript中创建和使用自定义错误的所有可能机制。

Also to get a complete understanding, it's essential to have an understanding of prototypal inheritance and delegation in JavaScript. 另外,为了获得完整的理解,必须了解JavaScript中的原型继承和委托。 I wrote this article which explains it clearly. 我写了这篇文章,清楚地解释了它。 https://medium.com/@amarpreet.singh/javascript-and-inheritance-90672f53d53c https://medium.com/@amarpreet.singh/javascript-and-inheritance-90672f53d53c

I hope this helps. 我希望这有帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 这是我用typescript创建javascript命名空间的正确方法吗? - Is this the correct way for me to create javascript namespaces with typescript? 创建Javascript类的正确方法是什么? - What is the correct way to create a Javascript class? 有没有正确的方法将自定义Javascript添加到ASP.NET MVC 5页面? - Is there a correct way to add custom Javascript to an ASP.NET MVC 5 page? 正确的方法添加自定义Javascript需要液体变量作为应用程序Shopify - Correct way to add custom Javascript needing Liquid variables as App to Shopify 使用 Javascript 创建和删除/销毁 DOM 元素的正确方法 - Correct way to create and remove/destroy DOM element using Javascript 使用纯 javascript 创建动画或效果的正确方法是什么? - What is the correct way to create animations or effects with pure javascript? 在 JavaScript 中创建 class 并将其传递给 MVC controller 的正确方法是什么 - What's the correct way to create class in JavaScript and pass that to MVC controller Javascript - 创建自定义错误并确保构造函数参数有效 - Javascript - Create custom errors and make sure that constructor params are valid 在Javascript中是否有正确的间距方式? - Is there a correct way of spacing in Javascript? 避免空属性错误的正确方法 - Correct way to avoid errors on empty properties
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM