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

查看:140
本文介绍了在JavaScript中扩展错误的好方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的JS代码中抛出一些东西,我希望他们是错误的instanceof,但我也想让它们成为别的东西。



在Python中通常情况下,将会对Exception进行子类化。



在JS中做什么适当的事情?

解决方案

只有标准字段错误对象是消息属性。 (请参阅 MDN 或EcmaScript语言规范,第15.11节)



Mosts环境设置堆栈属性,但 fileName lineNumber 几乎无用于继承。



所以,简约的方法是:

  function MyError(message){
this.name ='MyError';
this.message = message;
this.stack =(new Error())。
}
MyError.prototype = new Error; //< - 删除这个,如果你不
//要MyError作为instanceof错误

您可以嗅探堆栈,从中删除不需要的元素,并提取诸如fileName和lineNumber的信息,但这样做需要有关当前运行的JavaScript平台的信息。大多数情况是不必要的 - 如果您真的想要,您可以在验尸后进行。



Safari 是一个显着的例外。没有堆栈属性,但 throw 关键字集 sourceURL 正在抛出的对象的属性。



我使用的测试用例可以在这里找到: JavaScript自制错误对象比较


I want to throw some things in my JS code and I want them to be instanceof Error, but I also want to have them be something else.

In Python, typically, one would subclass Exception.

What's the appropriate thing to do in JS?

解决方案

The only standard field Error object has is the message property. (See MDN, or EcmaScript Language Specification, section 15.11) Everything else is platform specific.

Mosts environments set the stack property, but fileName and lineNumber are practically useless to be used in inheritance.

So, the minimalistic approach is:

function MyError(message) {
    this.name = 'MyError';
    this.message = message;
    this.stack = (new Error()).stack;
}
MyError.prototype = new Error;  // <-- remove this if you do not 
                                //     want MyError to be instanceof Error

You could sniff the stack, unshift unwanted elements from it and extract information like fileName and lineNumber, but doing so requires information about the platform JavaScript is currently running upon. Most cases that is unnecessary -- and you can do it in post-mortem if you really want.

Safari is a notable exception. There is no stack property, but the throw keyword sets sourceURL and line properties of the object that is being thrown. Those things are guaranteed to be correct.

Test cases I used can be found here: JavaScript self-made Error object comparison.

这篇关于在JavaScript中扩展错误的好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆