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

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-catch blocks are used for. If you can catch an exception and do something with that exception then go ahead and catch it. For example, BadHtmlException or 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-catch unless 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.

What you could do, is have a try/catch block around the code, putting a console.log() call in the catch block. This way, consumer's code will still run, but when debugging, they'll see that something went wrong within your library and notify you.

Related

PDF.js HTA, promise being rejected

I'm trying to develop an HTA for extracting and processing the data from PDF files for a number of people in a large office. I've been looking into using the PDF.js package for this, but I've not been able to get it working.
I've forked the project and created an HTA version of the helloworld example with the compatibility.js file included. I can get an HTML version of this working on Firefox and IE11 through a gulp server, but the HTA doesn't give any output - no text, no error messages.
After peppering the source files with alert() statements, I've discovered that the original hello.js file is missing promise reject function, and that this fires when added, but here where my I meet the limits of my knowledge. I don't really know an awful lot about promises, so I don't understand why this one fails. Is this solvable or does it mean that the package simply won't run in an HTA?
EDIT:
I've been looking more into this and the failure doesn't make sense.
Tracing the logic through, the hello.js file calls the function api.getDocument from api.js. Following this back, there is only one return statement and the alert statement just before this line is running. However the fulfilled function is not triggering.
From my very limited understanding, the failure clause on a promise will be triggered from a throw() statement within the asynchronous operation. If that is the case then I would expect that operation to immediately cease and the reject function to trigger, but why would the line immediately before the return statement still run?
I did pursue one theory that this line from api.js was the one throwing the error:
}).catch(task._capability.reject);
To check this, I added an alert statement to the reject() function statement in util.js, but it did not trigger, so I can't tell where the error is coming from.
Is anyone able to give me any additional pointers to help me trace this down?
Solved!
By changing the compatibility setting to IE10 instead of IE9 (which I didn't know I could do) I got a more useful error in the right place. Looking more into this, this issue appears to be a duplicate of this one:
Access denied in IE 10 and 11 when ajax target is localhost

Programatically retrieve count of javascript errors on page

I'd like to write a test case (using Selenium, but not the point of this question) to validate that my web application has no script errors\warnings or unhanded exceptions at certain points in time (like after initializing a major library).
This information can easily be seen in the debug consoles of most browsers. Is it possible to execute a javascript statement to get this information programatically?
It's okay if it's different for each browser, I can deal with that.
not so far read about your issue (as far as I understood your problem) here
The idea be the following:
I found, however, that I was often getting JavaScript errors when the page first loaded (because I was working on the JS and was introducing errors), so I was looking for a quick way to add an assert to my test to check whether any JS errors occurred. After some Googling I came to the conclusion that there is nothing built into Selenium to support this, but there are a number of hacks that can be used to accomplish it. I'm going to describe one of them here. Let me state again, for the record, that this is pretty hacky. I'd love to hear from others who may have better solutions.
I simply add a script to my page that will catch any JS errors by intercepting the window.onerror event:
<script type="text/javascript">
window.onerror=function(msg){
$("body").attr("JSError",msg);
}
</script>
This will cause an attribute called JSError with a value corresponding to the JavaScript error message to be added to the body tag of my document if a JavaScript error occurs. Note that I'm using jQuery to do this, so this specific example won't work if jQuery fails to load. Then, in my Selenium test, I just use the command assertElementNotPresent with a target of //body[#JSError]. Now, if any JavaScript errors occur on the page my test will fail and I'll know I have to address them first. If, for some strange reason, I want to check for a particular JavaScript error, I could use the assertElementPresent command with a target of //body[#JSError='the error message'].
Hope this fresh idea helps you :)
try {
//code
} catch(exception) {
//send ajax request: exception.message, exception.stack, etc.
}
More info - MDN Documentation

Prevent Javascript from Stopping when Error is Encountered

Our product inserts a script into client's websites, kind of like a live chat box.
Often, clients' websites have buggy javascript that also stops our code (the browser stops execution when errors are encountered). Is there any way to make our code still execute even though there are errors in the console about things like undefined methods or variables?
Thanks for your help.
The short answer is that you really can't.
"Solution" #1: You could insist that YOUR 3rd party code run before anyone else's. In most cases, this isn't possible or even desirable.
"Solution" #2: You could insist that the 1st party engineers wrap all 3rd party code in try/catch blocks. But, this solution really doesn't buy you any guarantee, because very frequently 3rd party libraries attach additional <script> tags to the page - these would not fall under the "jurisdiction" of the try/catch scope enclosing the code which created this/these tag(s).
"Solution" #3: You could build YOUR app entirely within the scope of an <iframe>, thereby avoiding the issue entirely. Unfortunately, even if you're very smart, you'll quickly run into cross domain violations, 3rd party cookie restrictions, and the like. It's very probable that this will not work for you.
"Solution" #4: You could explain the issue to your client, and have them demand that the other 3rd party code run cleanly. I say this is a "solution" because, frankly, it's not a "solution" to your question if your question is how to avoid doing exactly this.
Unfortunately, option #4 is your best bet. It may help if you observe other 3rd party libraries "breaking" in the same fashion: you can tell your client "hey, it's not just me - X, Y, and Z are all also 'broken' because of <name of other 3rd party library>." It may cause them to put the heat on the offending code, which makes the web a happier place for all involved.
As others have said, continuing after an error might not be the best thing to do but you can try this:
function ignoreerror()
{
return true
}
window.onerror=ignoreerror();
More details here
The onerror event fires whenever an JavaScript error occurs (depending
on your browser configuration, you may see an error dialog pop up).
The onerror event is attached to the window object, a rather unusual
place to take refuge in, but for good reason. It is attached this way
so it can monitor all JavaScript errors on a page, even those in the
section of the page.
Opera has a page with more details
Browsers supporting window.onerror
Chrome 13+
Firefox 6.0+
Internet Explorer 5.5+
Opera 11.60+
Safari 5.1+
You can't from your code - they need to use try/catch for questionable pieces of script.
You could have them insert an iframe into their page instead of you trying to inject code using a script tag like so: http://jsfiddle.net/EzMGD/ Notice how the script throws an error yet we can still see the content in the iframe. The iframe should help from using each others variables if applicable.
<script>
MeaningOfLife();
</script>
<iframe src="http://bing.com"></iframe>​
Or inject the code so it's the very first or very last script.
Well, to me that work fine:
element = document.querySelector('.that-pretty-element');
if (element != null) {
element.onclick = function () {
alert(" I'm working beibi ;) ");
}
}
querySelector() returns false, so, we can verify with if's

JavaScript - is it possible to force code execution after an error?

I'm trying to make a PoC of reflected Cross-Site Scripting on a website that I'm testing right now. I've found a place inside of a Javascript code where commands can be injected, however the trouble is that there the previous block of code throws a 'not defined' error and therefore (at least I think so) my injected code is not executed. Is there any chance to execute the code anyway?
Here is the code:
UndefinedObject.Init({
Var1:"a",
Var2:"b",
Var3:"can_be_injected_with_JS_code")}
I can't inject any HTML tags as these are filtered by the application.
Many thanks!
Wrap them under try catch block.
In a sequence of execution, if the code fails, the remaining part will not be executed. Javascript errors ("Exceptions") can be caught using try...catch (if you are able to inject this try - catch also).
If there is a different flow (via another event), the code will continue.
You can either try using a try-catch, or if that won't help, try using window.onerror
Generally the right way of doing that is using try-catch-finally or try-finally:
If you make something about the error - log or do something else. Catch may be also used to execute your code, but not a good practice. You can do nothing about the error if you want, that`s why finally is used.
Finally is used when it is important to execute a piece of code, no matter if an error is thrown or not. For example in C++ or other language when you work with files inside finally the file is closed ( you can not leave it opened ). Look here for some examples.

Add global try/catch to 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?
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.
Turn on the debugger and break on error.
You don't want to catch every error in the entire page on production code. That's horrible.

Categories