Vincent Duprez
Vincent Duprez

Reputation: 3892

Alert Javascript Errors when javascript fails?

When I have a fatal error in javascript making the app not usable, like this one:

SyntaxError: Unexpected token '}'

Is it possible to catch it and display it somehow? like replacing the body or alerting?

So in other words, a way to run javascript code if there is a javascript code error...

I can't open the web inspector on runtime when I'm inside a crashed page, this is because I'm using webkit outside of a browser who would normally be able to open and display the webinspector on a crashed page.

Upvotes: 3

Views: 78

Answers (2)

raina77ow
raina77ow

Reputation: 106385

Define window.onerror callback in the very first <script> loaded on the page, like this:

<script>
window.onerror = function(msg, url, line) {
    alert(msg + ' appeared on the line #' + line);
}
</script>

Upvotes: 5

Kasper Sanguesa-Franz
Kasper Sanguesa-Franz

Reputation: 617

You can use

try{
    adddlert("Welcome guest!");
}catch(err){
    alert(err.message);
}

Upvotes: 0

Related Questions