Third-party JavaScript - good idea to use try catch?

I am developing a third-party JavaScript widget that will be enabled by users in their applications / blogs. I have good tests in the library, but I'm afraid that, despite this, if some kind of syntax error breaks and causes other scripts in the user application to stop loading.

So - to prevent this from happening, is it useful for me to surround all widget code in try / catch like this?

try { // my library } catch(e) { // notify me about the error } 
+8
javascript
source share
2 answers

Here is a good general approach to what try-catch blocks are used for. If you can catch an exception and do something with that exception, then understand it and catch. For example, a BadHtmlException or something similar is an exception that you can catch to provide the user with feedback so that you correct the HTML and try again.

There are exceptions in which there are no actions that can be performed. For example, the application was configured incorrectly with a bad user / password. This should be a critical mistake and should go all the way to the application. An exception is possible that may not make sense to the user.

So what do I suggest? I suggest not wrapping anything in try-catch unless you know that this exception will be thrown. If there is an error or exception, the person using your code should see it and report it as a problem. You really cannot spend all your time on possible problems that may or may not be your code.

Finally, you should write unit tests and make sure that every part of your library is well tested before each version. Doing this ensures that future versions do not break anything.

+1
source share

What you can do is have a try / catch block around the code by introducing a console.log () call into the catch block. Thus, the consumer code will still work, but when debugging, they will understand that something went wrong in your library and notified you.

0
source share

All Articles