Error
The Error object is a custom extension of the native Error object with methods for gathering information about an error.
General usage
It is not possible to extend the native Error object by prototyping but the object itself serves as a convenient placeholder for functions related to error handling.
The functions defined by JSLab need an error object to work with. They are designed to be used in catch blocks. The functions are not compatible for assigning as event handlers to the window.onerror event but Opera and Safari doesn't support this event anyway.
To gain access to an error object lets make an example with an intentional error
1 // Function with intentional error 2 function myFunc(s) { 3 alert(s); 4 // Undeclared variable 5 notDeclared 6 }
By executing the function in a try block an Error object e becomes available in the catch block when an error occurs
1 // Execute myFunc in try block to catch error 2 try { 3 myFunc('Hello world'); 4 } 5 catch(e) { 6 // Get error report with verbosity level 1 7 alert(Error.report(arguments.callee, e, 1)); 8 }
The Error.report function will gather information about the error (filename, line number), the client (OS, browser etc.), stacktrace and possible an event object if one exist in the function throwing the error. See a demonstration.
The report is a string which can be send to the server for logging or you may use it any way you like.
Automating error handling
By using the setErrorHandler method of the Function object you can automate error handling and assign error handles dynamically.
This example shows how to assign the Error.report function as an error handler for a given function
1 // Suppose init() is called onload 2 function init() { 3 // Set error handler for myFunc 4 myFunc = myFunc.setErrorHandler(Error.report); 5 // Execute myFunc 6 var returnValue = myFunc('Hello world'); 7 }
If an error occurs inside myFunc it will be automatically reported and returned to the returnValue variable.
For more information on error reporting see the article Auto reporting JavaScript errors.
