JavaScript Error Handling
Errors
When a runtime error occurs, web browsers show specified error messages and may offer the possibility to examine this error with an debugger.
By applying an function pointer to window.onerror, it is possible to handle this error by the specified function and optionally disable the browser’s error handling by returning true.
window.onerror = handleError;
The function takes three parameters:
messagethe error messagelocationfilename of the script containing the erroneous codenumberthe error’s code number
function handleError(message, url, code){
//..
return true;
}
Unfortunately, every browser behaves a bit different:
- Internet Explorer handles errors to the given function
- Firefox handles errors and can handle uncaught exceptions to the function
- Safari only shows the error in the JavaScript Console
- Opera might show the error in the error console
Exceptions
Thrown exceptions can be handled to a specified function to perform further examinations.
try
{
var foo = '';
foo.bar();
}
catch (exception)
{
handleException(exception)
}
The exception object contains the following properties:
- name the name of the exception (e.g.
TypeError,SyntaxError) - message a text describing the error
In some browsers the object has more properties:
- Internet Explorer:
numbererror codedescriptiondescription of the error (mostly identical to message)
- Firefox:
stackcall stackfileNamename of the script containing the erroneous codelineNumberline which contains the error
message property contains the call stack.
