I'd like to catch all client-side JavaScript errors on our site and log them. What are some best practices for doing this?
Thoughts:
/log/
handler to our webapp, parse GET/POST parameters and use our existing logging system on the server-side. Is that too obvious?window.onerror
work everywhere? What if an error occurs in the handler?<img>
tag to the page or make an XmlHttpRequest? What if the XHR fails?The Error object and error. It contains 3 standardized properties: message, fileName, and lineNumber. Redundant values that already provided to you via window. onerror .
onerror is a DOM event handler. It is started when an error occurs during object loading. While window. onerror is an event handler, there is no error event being fired: instead, when there is an uncaught exception or compile-time error, the window.
onerror is a special browser event that fires whenever an uncaught JavaScript error has been thrown. It's one of the easiest ways to log client-side errors and report them to your servers. It's also one of the major mechanisms by which Sentry's client JavaScript integration (raven-js) works.
JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally block, similar to other languages like Java or C#. try: wrap suspicious code that may throw an error in try block. catch: write code to do something in catch block when an error occurs.
All suggestions made by Jbecwar and dgvid are cool, I would add:
As Jbecwar suggests, the log handler is a good idea, but you need to watch out for a condition in which you try to call the log handler to report an error contacting the log handler. If the browser loses its connection to the server, you aren't going to be able to log that back to the server.
You can catch an img load failure by attaching an error handler to the img element, then setting its src attribute. For example, using jQuery:
$("img#my-image").error(onImgError).prop("src", "images/my-image.jpg");
You won't get much information that way, just the fact that an error occurred while trying to load the specified element.
You can handle failures in jQuery.ajax requests by including an error callback function in the settings object passed to $.ajax. Be sure to wrap the code in both the success and error callback functions in try-catch.
Generally, you will want to protect your code with try-catch blocks so that you can catch and log errors. Handling window.onerror should be a last resort - for the things that slip through.
In your window.onerror handler, wrap everything in a try-catch block and ensure that you will not throw from the code in the catch block (using nested try-catches, if necessary).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With