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.
Related
Is there a static code analysis tool that would tell me that there are places in my code that don't handle possible error events?
I had an important script crash because I used new WebSocket without registering an on('error') - even though the place where the websocket was created was in a try/catch block. And I'd like to prevent similar situations again.
Not directly answering your question about static analysis -- which always has limits -- but you can prevent crashes like this from bringing down your service by adding a catch-all:
process.on('uncaughtException', (err) => {
console.error(`**** Caught exception: ${err}:`, err.stack);
});
Clearly, you should try hard not to rely on this, because the code blocks where such exceptions are thrown will not complete as intended. But it's a useful safe-guard to have to avoid downtime.
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.
I have a lot of JavaScript code that get's executed on a website. If every plugin works, everything is fine. But when only one JavaScript error occurs, all other code fails, too.
I am concatenating all JavaScript code to one file. This is currently a must, so a change here is not possible.
What's the general way of preventing (vendor) code not fail everything else?
EDIT:
To simplify my question: What's the best way of handling big JavaScript error from vendor code?
Your error handling should be as simple as the following example:
try{
var x = functionThatDoesNotExist();
}
catch(error){
console.log('An error occured');
console.log(error);
}
You should try and break down your javascript files according to the templates that contain your HTML markup, and simply when an error occurs do not render that template.
You can read more on Try/Catch here.
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.
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.