0

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.

Nagaraj Tantri
  • 5,172
  • 12
  • 54
  • 78
radbyx
  • 9,352
  • 21
  • 84
  • 127
  • Just saw in the answer, might be a duplicate then: http://stackoverflow.com/questions/2604976/javascript-how-to-display-script-errors-in-a-popup-alert/ – Nagaraj Tantri Jan 10 '14 at 08:29

2 Answers2

5

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

Community
  • 1
  • 1
Frolin Ocariza
  • 210
  • 1
  • 8
  • Further help for the user: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch – Nagaraj Tantri Jan 10 '14 at 08:23
  • I was looking where I don't have to wrap all my functions in try-catchs. So I could defined it one time one place. If it's possible. Ok i'll check window.onerror soon, it looks very promising – radbyx Jan 10 '14 at 11:56
0

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!

Magnus Wallström
  • 1,469
  • 4
  • 15
  • 23
  • Thanks. But im sorry i forgot to mention that i wanted a higher abstractionlevel that try catch. – radbyx Jan 10 '14 at 11:58