Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

javascript - 什么是在JavaScript中扩展错误的好方法?(What's a good way to extend Error in 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.(我想在我的JS代码中抛出一些东西,我希望它们是instanceof Error,但我也想让它们成为别的东西。)

In Python, typically, one would subclass Exception.(在Python中,通常会有一个子类Exception。) What's the appropriate thing to do in JS?(在JS中做什么是合适的?)   ask by Josh Gibson translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The only standard field Error object has is the message property.(唯一的标准字段Error对象是message属性。)

(See MDN , or EcmaScript Language Specification, section 15.11) Everything else is platform specific.((参见MDN或EcmaScript语言规范,第15.11节) 其他所有内容都是特定于平台的。) Mosts environments set the stack property, but fileName and lineNumber are practically useless to be used in inheritance.(大多数环境设置stack属性,但fileNamelineNumber实际上无用于继承。) 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.(您可以嗅探堆栈,从中移除不需要的元素并提取fileName和lineNumber等信息,但这样做需要有关当前正在运行的JavaScript平台的信息。) Most cases that is unnecessary -- and you can do it in post-mortem if you really want.(大多数情况是不必要的 - 如果你真的想要,你可以在验尸中做到。) Safari is a notable exception.(Safari是一个值得注意的例外。) There is no stack property, but the throw keyword sets sourceURL and line properties of the object that is being thrown.(没有stack属性,但throw关键字设置了要抛出的对象的sourceURLline属性。) Those things are guaranteed to be correct.(这些事情保证是正确的。) Test cases I used can be found here: JavaScript self-made Error object comparison .(我在这里可以找到测试用例: JavaScript自制的Error对象比较 。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...