frenchie
frenchie

Reputation: 51927

javascript on error reload page

I am wondering how to best handle javascript errors. My application is pretty javascript intensive and although I'm doing everything possible to test my code, I know that bugs will be inevitable.

Is there a way catch errors and reload the page when they occur? I know about try/catch but rather then adding a bunch of these, I was wondering if there's a way to add something in document.ready that execute a page reload on error.

Thanks for your suggestions.

Upvotes: 0

Views: 5449

Answers (3)

pete
pete

Reputation: 25081

Well... you could also wrap the contents of the document.ready in a single try catch block. Then, in the catch call window.location.reload();, although I'm not sure what benefit you or the user get from automatically reloading the page on an error. If you get the error once, page reloads, which gets the error again, which reloads the page again, which gets the error again, which... ad nauseam.

Upvotes: 0

Andy Hume
Andy Hume

Reputation: 41664

You can use the window.onerror event to catch errors that bubble up to the window.

Eg,

window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
    // deal with error
    return false;
}

I definitely wouldn't recommend just refreshing the page on error, as there may be more graceful ways of failing or even recovering. Also, you could theoretically get into an endless loop of refreshes.

Upvotes: 0

SLaks
SLaks

Reputation: 887225

You're looking for the window.onerror event.

Beware that if an error occurs on page load, you may end up recursing.

Upvotes: 2

Related Questions