DelphiFAQ Home Search:

Catch javascript error messages before they pop up

 

comments1 comments. Current rating: 5 stars (1 votes). Leave comments and/ or rate it.

Since version 1.1 client side Javascript has an event driven error handling model where you define a handler function for window.onerror to overwrite the 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.

The sample code below shows an easy-catch-all handler and an advanced one which actually looks into the passed error information and tries to do something reasonable. The advanced version also restores the browser's default handler when done.

//------------------------------------------------------------
// suppress all error messages and do nothing with them:
//
function noErrorMessages () { return true; }
window.onerror = noErrorMessages;

//------------------------------------------------------------
// advanced: a full error handler
//
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.defaultOnError = window.onerror; // store default handler
window.onerror = handleError; // assign own handler

//.. executing my faulty code

window.onerror = window.defaultOnError;  // restore default handler

Comments:

2009-11-08, 02:10:53
anonymous  
rating
thanks

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: