Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add global try/catch to JavaScript

Tags:

javascript

Is there some way to wrap the entire page in a try/catch, so that I can catch any error from any script that is executing?

like image 696
David Martines Avatar asked Feb 04 '11 18:02

David Martines


People also ask

Where do I put try catch in JavaScript?

The try-catch statement should be used any time you want to hide errors from the user, or any time you want to produce custom errors for your users' benefit. If you haven't figured it out yet, when you execute a try-catch statement, the browser's usual error handling mechanism will be disabled.

Is there a try catch in JavaScript?

JavaScript try and catchThe try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.

Should I try catch everything JavaScript?

For what it's worth, blanketing your code with try-catch statements is a pretty bad idea. If there's an error, you should resolve it, not allow it to happen but suppress it via try-catch. +1 for wanting to properly try catch all your functions.

Can you nest try catch blocks JavaScript?

You can nest one or more try statements. If an inner try statement does not have a catch -block, the enclosing try statement's catch -block is used instead. You can also use the try statement to handle JavaScript exceptions. See the JavaScript Guide for more information on JavaScript exceptions.


1 Answers

Use window.onerror instead of a big try/catch.

You could actually do some useful things in the error handler, like posting the error information to your server so you know when things are breaking on your page.

like image 186
Jonathon Faust Avatar answered Sep 21 '22 23:09

Jonathon Faust