How to ignore an error in Vanilla JavaScript - javascript

I am running a Tampermonkey script on a website that I do not have the code for.
Sometimes it happens that I have a value that does not exist on the page and I get the following error:
"Cannot read property 'click' of null"
And the entire script stops. How can I tell get my script to ignore the error and just carry on to the next line of code?
Here is an example of a vanilla Javascript line that I work with:
document.querySelector('[value="xyz"]').click();

Only execute click() if the selector found something:
if(document.querySelector('[value="xyz"]'))
document.querySelector('[value="xyz"]').click();

You can't, and you shouldn't want to: errors are bad. They're not informative, they are a signal that the code has run into an unrecoverable error and the current code path should be terminated. If you were to ignore it, and keep running, now you're in a state where any subsequent line is just as likely to also throw an error.
Either actually fix things, by making your tampermonkey script not interfere with the way the page it's running on builds its DOM, or as a last resort, you can find out which function is throwing the error for the specific page(s) you're running into this, and then _specifically for those pages, find and rebind the entire function using a try/catch, such as:
const _old_fn = window.theFunctionInvolved;
window.theFunctionInvolved = function(...args) {
try { return _old_fn(...args); }
catch (e) {}
};
But of course, all you've now done is moved the buck: you'll have effectively guaranteed different errors later on, with the actual cause now permanently hidden.
So really: don't do this. Fix your tampermonkey script, or stop using it altogether.

Related

how to force js ignore uncaught error and continue to work?

When run javascript app integrating with some 3rd party library, in some cases , 3rd party lib will lead to bug , for example, following typical error:
Uncaught (in promise) TypeError: Cannot read property 'length' of undefined
The above error is ok to some extend because their code quality is not well(good code should always check if object exist,array length>0 etc before access them), what i concern is: i do not want the js app functions as if they crashed and not work anymore, even if the root cause which should cause above error disappear(for example, the array has been there now), the app will never survive to run again.
Is there some method to force js app to run even after 3rd party code fail(or my own code fail) but should SURVIVE to run for some other function area(which has no the crash causing there), or survive to work again if the cause for above exception disapper?
Please NOTE THAT, I DO NOT WANT TO TOUCH 3RD party code to let this work
Is there a generic mechanism in javascript to be switched on : just skip the un-caught error and continue to run as normal and NOT CRASH the app?
If you don't want to use try-catch
process.on('uncaughtException', err => {
console.error('There was an uncaught error', err)
process.exit(1) //mandatory (as per the Node.js docs)
})
If you don't exit the process, It can cause unexpected behaviour in your application which's why it recommended.
Further reading
As Nirus said, wrapping everything that could cause an error in a try...catch block:
try{
callYourLibHere();
}
Block should allow the code to ignore errors thrown, which will make the code continue to run after an error occurs. However, this will hide EVERY error inside this block. We can fix this by logging the errors into the console:
try {
callYourLibHere();
}
catch (e) {
console.log(e);
}
Please note that trying to solve the errors instead of ignoring them would be the better way to fix this.

javascript error stops runtime execution

We had a situation today where 1 small error (on line 500) in our JS library file (3000+ lines long) caused a runtime error (calling a method on an undefined object).
The error stoped further execution of all other code in the library file causing our site to not work properly.
My question is:
Since JS is single threaded, will splitting up our code into multiple files and scopes help resolve issues like that in the future?
If we don't split it up, how can we prevent this from happening.
thx,
You can't : js scripts are loaded at once.
The only way to prevent it is to design your code correctly, using try/catch and to write and run tests
Simple solution would be to check if the object exists before attempting to call the method on it.
if ( myObject && myObject.myObjectFunction )
myObject.myFunction();
else
return false;
If the object exists and the object has the function you want to call then it'll call the function, otherwise it'll return false and not attempt to call the function, thus avoiding the error entirely.

Javascript URL Navigation Handling Interfering with other Javascript Sections

Two aspects of my project's Javascript are interfering with each other. Not sure why, or how to resolve.
I have the following in my code, in order to allow for a URL hashtag action:
function getHashValue(key) {
return location.hash.match(new RegExp(key+'=([^&]*)'))[1];
}
var hash = getHashValue('hash');
console.log(hash);
I'm also running video.js and bigvideo.js within my Rails project. For some reason, the javascript code above prevents the other javascript (my bigvideo implementation) from functioning. Why? How do I resolve?
My bigvideo implementation is described here: https://stackoverflow.com/a/17581187/1318135
It seems possible that getHashValue is throwing an exception (array limit exceeded?) which could interfere prevent other code on the thread from running. Try enclosing the return statement in a try/catch.
Here's what you get: TypeError (exception) Cannot read property '1' of null.
Catch the exception and you'll be okay, I think.

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

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.

Categories