Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the actual Javascript Error object with window.onerror

Javascript has this great callback window.onerror. It's quite convenient to track any error. However, it calls with the error name, the file name and the line. It's certainly not as rich as getting the actual error object from a try...catch statement. The actual error object contains a lot more data, so I am trying to get that. Unfortunately, try...catch statement do not work fine when you start having async code.

Is there a way to combine and get the best of both worlds? I initially looked for a way to get the last error triggered within an onerror block, but it looks like JS doesn't store that.

Any clue?

like image 800
Julien Genestoux Avatar asked Aug 17 '11 20:08

Julien Genestoux


People also ask

How do you check if an object is an error in JavaScript?

To check if a variable is of type Error , use the instanceof operator - err instanceof Error . The instanceof operator returns true if the prototype property of a constructor appears in the prototype chain of the object. Copied!

What does Onerror do in JavaScript?

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.

What is Onerror event?

The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image). Tip: When used on audio/video media, related events that occurs when there is some kind of disturbance to the media loading process, are: onabort. onemptied. onstalled.

How do you return an error in JavaScript?

To return errors from functions as promises, there are generally two ways to produce rejected promises: The reject function of your Promise library. Throwing an exception in a then callback or returning a rejected promise from it will reject the resulting promise.


1 Answers

this is now possible in some browsers. The spec was updated to include the actual error with stacktrace as the 5th parameter.

the problem is that not every browser supports this yet, so you could do something like this:

window.onerror = function(message, filename, lineno, colno, error) {     if(error != null)     {         //handle the error with stacktrace in error.stack     }     else     {         //sadly only 'message', 'filename' and 'lineno' work here     } }; 
like image 153
Archaeron Avatar answered Oct 05 '22 06:10

Archaeron