I am developing a third party JavaScript widget that will be included by users on their applications/blogs. I have good tests around the library, but I am afraid that if despite that if some syntax error sneaks through and cause the other scripts on the user’s application to stop loading.
So – to prevent this from happening, is it a good idea to surround my entire widget code in a try/catch like this?
try {
// my library
} catch(e) {
// notify me about the error
}
Here is a good common approach to what
try-catchblocks are used for. If you can catch an exception and do something with that exception then go ahead and catch it. For example,BadHtmlExceptionor something similar is an exception you can catch to provide user with feedback that you should fix the HTML and try again.There are types of exceptions that there is no action that can be done. For example, the application was configured incorrectly with a bad user/password. This should be a critical error and should be push all the way up to the application. Possibly an exception that might not make sense to the user.
So what am I suggesting? I am suggesting don’t wrap anything in a
try-catchunless you know there will be that exception thrown. If there is a bug or exception, the person using your code should see it and report it as an issue. You really can’t spend all your time going through possible issues that may or may not be your code.Finally, you should write unit tests and make sure each part of your library is well tested before each release. Doing this will make sure that future releases don’t break anything.