faqts : Computers : Programming : Languages : JavaScript : Event handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

127 of 150 people (85%) answered Yes
Recently 8 of 10 people (80%) answered Yes

Entry

How can I handle JavaScript errors?
How can I suppress JavaScript error messages?
How can javascript 1.5 use window.onerror
Where is there full documentation on javascript 1.5 events

Feb 14th, 2000 16:40
Martin Honnen, John Middlemas,


JavaScript 1.4+ and JScript 5+ do have exception/error handling as 
part of the core language in the form of the try/catch statement:
  try {
    statements
  }
  catch (err) {
    // handle error
  }
Unfortunately this feature is not around in client side javascript in 
NN2/3/4 and IE browsers differ depending on the version of JScript 
installed.
Client side javascript starting with 1.1 has an event driven error 
handling mechanism where you define a handler function for 
  window.onerror
to overwrite the browsers error handling. The error handler has 
three arguments error message, url and line number. It should 
return true if the error is handled and return false to let the 
browser handle the error. Example:
  function handleError (err, url, line) {
    if (err.indexOf('is not defined') != -1) {
      alert('Oops, something is not defined.\n' +
             err + '\n' + url + '\nline no: ' + line);
      return true; // error is handled
    }
    else
      return false; // let the browser handle the error
  }
  window.onerror = handleError;
That means it is possible to suppress the browsers error messages with
  function noErrorMessages () { return true; }
  window.onerror = noErrorMessages;
It is also possible to temporarily assign your own error handler and 
then later restore the standard error handling with
  window.defaultOnError = window.onerror; // store default handler
  window.onerror = handleError; // assign own handler
  ...
  window.onerror = window.defaultOnError;  // restore default handler