radbyx
radbyx

Reputation: 9650

Show an alert or popup if a Javascript error occurs

Is it possible to get visuel notifyed if I get a Javascript error?

In developing I have Firebug or something else open so I spot it. But in the case where I do a light demostration for someone else I can not have it open.

I still prefer to know about the error instead of it failing silently and I dont know about trailings errors where I can't distinct wish between real and trailing errors.

Upvotes: 0

Views: 2547

Answers (2)

Frolin Ocariza
Frolin Ocariza

Reputation: 210

You can surround your code in a try-catch and call alert with the error message. For example, if your code is as follows:

var x = document.getElementById("wrong_id"); //returns null
x.innerHTML = "Hello world!"; //null exception

you can surround it with the try-catch as follows:

try {
    var x = document.getElementById("wrong_id"); //returns null
    x.innerHTML = "Hello world!"; //null exception
}
catch(err) {
    alert(err.message);
}

err.message basically contains the error message, similar to the one you see in Firebug.

Edit: You may also define window.onerror. See this answer

Upvotes: 5

Magnus Wallström
Magnus Wallström

Reputation: 1529

I believe you can use try catch functionality to show the error.

Something like this:

try {var a = 20 / f;}
catch (err) {alert(err);}

http://jsfiddle.net/magwalls/h7kqr/

Hope this helps!

Upvotes: 0

Related Questions