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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…