Well, as JavaScript is executed in the client-side, I can't control a bunch of environment variables and, at some point, my app will probably throw an exception.
What I want to do is to get this exception and make my app fail gracefully and show the maximum information as possible to the end user (my end users are technical ones). Obviously, the error handling can be done through a simple try...catch block.
What is annoying me is: how can I know what information is stored in a native exception caught by the catch
block?
I assume that the native exceptions thrown by the JS engine of the browser are just objects from the Error
classes, as by running this code:
try {
a;
} catch (ex) {
console.log(ex);
console.log(new ReferenceError("`Custom` error"));
}
I get the same structure:
ReferenceError: a is not defined
at http://stacksnippets.net/js:14:3
ReferenceError: `Custom` error
at http://stacksnippets.net/js:17:15
Well, the console.log
of a normal object is slightly different than this, but assuming that the ex
variable is an object, I could loop through it by a for...in
, right?
Well, no.
This code doesn't show anything in the log:
try {
a;
} catch (ex) {
for (prop in ex) {
console.log(prop, ": ", ex[prop]);
}
}
So, my question is: How can I get all the information stored in a native JavaScript exception?
Yes, I know that I could access the properties directly by ex.name
, ex.description
, ex.message
, ex.stack
, and so on, but I would like to avoid that. Some browser can implement something that another browser don't have, so I will be missing some information when running in the first one (as you can see by this question, the stack
property, for example, was first implemented by Firefox).
And, if someone can explain, I would like to understand what is the real nature of the JavaScript exceptions (are they objects? why they look so different in the console?) and why can't I loop though it with a for...in block (probably the answers are very related).
Thanks.