Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch javascript exceptions/errors? (To log them on server)

Duplicate:

  • Automatic feedback on JavaScript error
  • Logging JavaScript-Errors on Server

How would I go about logging errors in javascript? I can't wrap every line of javascript in try catch block.

I talking about the errors that for example in IE, would show an Error On page message and have the line and char the caused the error. If I can just figure out how to catch this error on the client side, I can just log the error on the server using an ajax call.

like image 986
jdelator Avatar asked Apr 22 '09 23:04

jdelator


People also ask

How do I check for JavaScript errors?

Right-click anywhere in the webpage and then select Inspect. Or, press F12 . DevTools opens next to the webpage. In the top right of DevTools, the Open Console to view errors button displays an error about the webpage.

Can you throw error in catch block JavaScript?

The catch statement lets you handle the error if any are present. The throw statement lets you make your own errors. The finally statement lets you execute code, after try and catch. The finally block runs regardless of the result of the try-catch block.

Does JavaScript support try catch?

JavaScript try and catchThe 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.


1 Answers

I use this function in all my projects:

window.onerror = function(m,u,l){
    jQuery.post("ajax/js_error_log.php",
        { msg: m,
          url: u,
         line: l,
       window: window.location.href });
    return true};

Make sure it is the very first javascript the browser receives or at least precedes any potentially error-causing code. Requires jQuery of course, but you could code ajax functions in pure javascript if you wanted to.

Please note: this will not help you if you have a syntax error. All javascript instantly dies if there is a syntax error.

like image 84
Andrew Ensley Avatar answered Oct 13 '22 08:10

Andrew Ensley