Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Robust Javascript Exception Handling

I am developing a DHTML/Javascript application which relies on some advanced features (DOM manipulation, AJAX, Flash communication, and more). I'm very concerned about functionality -- if problems occur, even after the application is deployed, I want to make sure I know why and how to fix them -- and also, I want to make sure the user is able to continue using the application, possibly with reduced functionality if the exception was severe.

I currently have a logging and exception handling system built whereby functions can generate logs, and if an exception is caught, all logs are emailed to me. The system works well but I'd like to make it more robust. I'm looking for suggestions.

One idea I have is to wrap the body of every javascript function in a try/catch block and upon catching an exception, log the name of the function and then throw the error to the global handler. But that's a lot of code just to track down the function the exception occurred in.

Any ideas to make runtime exceptions easier to find and reproduce?

like image 492
Josh Avatar asked Jul 08 '09 23:07

Josh


People also ask

Is exception handling possible in JavaScript?

Exception handling is one of the powerful JavaScript features to handle errors and maintain a regular JavaScript code/program flow. An exception is an object with an explanation of what went amiss.

What is try catch in JavaScript?

The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. The JavaScript statements try and catch come in pairs: try { Block of code to try.


1 Answers

Rather than dealing with adding N try/catch blocks to N functions, it might be easier to use the window.onerror event.

JavaScript Kit has a series of examples you could use. Especially the 3rd:

window.onerror = function (msg, url, line) {
  alert('Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + line);
  return true;
}

If you'd prefer a stack trace, you might check out Eric Wendelin's (or Luke Smith's update). It's one of the few I know of that attempts to work cross-browser.

like image 144
Jonathan Lonowski Avatar answered Oct 02 '22 02:10

Jonathan Lonowski