I tried to extend the JavaScript error properties through the extension of the prototype of the Error constructor:
<script type="text/javascript">
// extending the Error properties to all the ones available in the various browsers:
Error.prototype = {
name: null, // (all browsers); the name of the error
message: null, // (all browsers); the error message as a string
description: null, // (Internet Explorer); description of the error
fileName: null, // (Firefox); the name of the file where the error occurred
lineNumber: null, // (Firefox); the number of line where the error occurred
columnNumber: null, // (Firefox); the number of column where the error occurred
number: null, // (Internet Explorer); the error code as a number
stack: null // (Firefox, Chrome); detailed information about the location where the error exactly occurred
};
function log(error) {
var errors = [];
for (var prop in error) {
errors.push(prop + ': ' + error[prop]);
}
alert(errors.join('\n'));
}
</script>
Then I test the log function:
<script type="text/javascript>
try {
var a = b; // b is undefined!
} catch(error) {
log(error);
}
</script>
The result is that the error object only shows some properties (e.g. on Firefox fileName
, lineNumber
and columnNumber
) like if it has not been extended.
But the most strange thing is that the for...in
cycle seems unable to walk all the error object properties: trying to alert the standard property error.message
normally returns a message.
So the results of my test are:
- the Error constructor is not extensible through its prototype, as other native constructors are;
- the
for...in
loop is not able to walk the properties of an error object.
Am I right?
Are there some interesting evidences/resources you may suggest to know more about it?
Error
is a host object and therefore does not have to behave like "normal" JavaScript objects.host object
on this site you'll find some interesting statements about them. edit: They are basically objects supplied the environment and not part of the specification (just like DOM objects, yes). But the problem is probably just thatError.prototype
is not writable (at least in Firefox).var obj = {foo: 'bar'}; Error.prototype = obj; Error.prototype == obj;
results infalse
.