I need to be able to run a bunch of code if a statement is successful. If javascript had a try/catch/else then I would put all the code in the else and be done with it. I don't want to use a Boolean to mimic the else in try/catch/else. My understanding is that try can handle an error but can't IF do the same? If so, I'll have to use the IF but I don't want my program to crash if the QueryInterface fails. So my question is, if the QueryInterface fails, then the else will be executed in the IF below correct? If so then I guess the only reason to use a try/catch is to snag the error condition.
existing method:
try {
channel = subject.QueryInterface(Ci.nsIHttpChannel);
} catch(err) {
booSuccess = false;
intErrorCount++
}
if (booSuccess == true) {
...bunch of stuff...
}
proposed method:
if (channel = subject.QueryInterface(Ci.nsIHttpChannel)) {
...bunch of stuff...
} else {
intErrorCount++
}
No, throwing an exception (which you catch with the first snippet) is very different from returning an error code (channel == 0, which the second snippet checks). They do not do the same.
What you might do to avoid that boolean variable is
try {
channel = subject.QueryInterface(Ci.nsIHttpChannel);
...bunch of stuff...
} catch(err) {
intErrorCount++
}
but that would also raise the error count if an exception happens in the bunch of stuff.
No you can't simply replace the try/catch with an if/else. If a line throws an error, the javascript interpreter will stop execution of that script.
Related
We can stub any function or class like this,
class ErrorStub{
constructor(message){
// do whatever with 'message'
}
}
Error = ErrorStub
new Error('This will go to ErrorStub now')
Similar to this, is there any way we can intercept a 'throw' statement. So that whatever exception is thrown across whole website, can be handled in one place?
Wouldn't this satisfy your needs? You would need to listen to the error event, handle it the way you want and return false
function interceptError(exception) {
// Here you can write code which intercepts before
// the error gets triggered and printed in the console
alert(`Exception occured: ${exception.message}`)
}
window.addEventListener("error", function (e) {
interceptError(e);
return false;
})
throw new Error('Test exception');
Let's say I have function below
var isallow = false;
function checkToAllow(){
if(isallow == false)
// stop execution of calling method( parent method)
}
function showMEVal(){
checkToAllow();
console.log("I am here because I am allowed");
}
so basicaly, showMEVal() method will first check that execution further is allowed or not, if it is allowed it will continue further, else it will exit.
This is to be common functionality to a number a function where it needs to be first checked whether it should be continue or not.
I dont want to explicitly work with returned values from checkToAllow() method, like
function showMEVal(){
if(checkToAllow() == true)
console.log("I am here because I am allowed");
}
I was thinking to use event.stopImmediatePropagation(); but it does not seems it will work.
Please advise
Thanks
The normal way to handle this is to throw an exception in the child function. You can read a brief description of exception handling in JavaScript at w3schools, here: http://www.w3schools.com/js/js_errors.asp.
So for your example, you'd have:
var isallow = false;
function checkToAllow() {
if(isallow == false)
throw CustomAbort(); // Can be anything: object or basic data type
}
function showMEVal(){
try{
checkToAllow();
}
catch (err) {
return;
}
console.log("I am here because I am allowed");
}
What makes this useful is that you only have to have the try... catch... construct at the very top level of your JavaScript, and only once. Then, deep down in your processing you can simply have:
function deepFunction() {
checkToAllow();
console.log("I am here because I am allowed.");
console.log("I'm not sure what happens if I'm not allowed, because it's taken care of by checkToAllow(), and by the top level error handling!")
}
You could probably also just throw anything from checkToAllow and provided nothing else is catching that error, it would propagate all the way up as a JavaScript error and stop the rest of your processing... but that's obviously not best practice, because no one wants JavaScript errors in their page!
Continuing with topic: jQuery .globalEval() function
I use jQuery.globalEval(varwithJScode);
Now the problem starts when code in varwithJScode contains syntax or other error - the whole script stops.
jsFiddle does not support jQuery.globalEval(), but I used eval() instead to simulate.
http://jsfiddle.net/55FfW/
Try changing var codeforeval to some wrong javascript code and next command will fail.
Is there a way to avoid other JS code from stopping in case of error and/or is there a way to check syntax before eval?
Tried using this one:
try {
jQuery.globalEval(jscode);
} catch (e) {
if (e instanceof SyntaxError) {
alert('JS error!');
}
}
Does not work for me!
try {
jQuery.globalEval(data.js);
} catch(e) {
console.log(e);
}
You need not a heavy jQuery to do such a simple thing.
Just assign eval to a variable and then call it.
try{
var globalEval = eval;
globalEval(jscode); //execute in global scope
} catch(e) {
alert(e);
}
Is there a way in Javascript to listen to on throw events?
I want to be able to have an event handler be called even when code like this is executed:
var hi = "hi";
try {
throw hi;
}
catch (e) {
}
In chrome (and maybe firebug too) you can run this code and hit "break on all errors" and it will break on that throw line. How exactly are they doing that? Is that outside of Javascript?
How they are doing that is the JavaScript engine doesn't continue over errors, it crashes on all error, like if you compiling c++, it is not a language feature, its the browser
That's not event that's exception, the handler goes in the catch-block:
try {
//....
}
catch (e) {
// exception handling here
// or may be fire/trigger some event here
}
The answer you accepted is not correct.
If you have an error that happens not within try {} catch() {} block, then the JavaScript execution will really break at that point.
However, if you wrap your possibly breaking code in try {} catch() {}, you can use re-throw the error to be handled by one global event handler:
window.onerror = function (error) {
// access `error` object
};
try {
// for example try to assign property to non-existing object
undefinedObj[property] = 1;
}
catch (error) {
// `error` object will be available in `onerror` handler above
throw new Error(error);
}
I wanted to know if it is possible to find through javascript if a call to eval() has a syntax error or undefined variable, etc... so lets say I use eval for some arbitrary javascript is there a way to capture the error output of that eval?
You can test to see if an error is indeed a SyntaxError.
try {
eval(code);
} catch (e) {
if (e instanceof SyntaxError) {
alert(e.message);
}
}
When using try-catch for catching a particular type of error one should ensure that other types of exceptions are not suppressed. Otherwise if the evaluated code throws a different kind of exception it could disappear and cause unexpected behaviour of the code.
I would suggest writing code like this:
try {
eval(code);
} catch (e) {
if (e instanceof SyntaxError) {
alert(e.message);
} else {
throw e;
}
}
Please note the "else" section.
According to the Mozilla documentation for eval:
eval returns the value of the last expression evaluated.
So I think you may be out of luck. This same document also recommends against using eval:
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller. If you run eval() with a string that could be affected by a malicious party, you may end up running malicious code on the user's machine with the permissions of your webpage / extension. More importantly, third party code can see the scope in which eval() was invoked, which can lead to possible attacks in ways of which the similar Function is not susceptible.
So regardless, please be aware of the risks before using this function.
You can use JsLint which contains a javascript parser written in javascript. It will give you lots of information about your code, it can be configured to be more relaxed or not, etc...
To continue using the code after validation, I use the following example:
var validCode = 1;
try {
eval( jsCode ); /* Code test */
} catch (e) {
if (e instanceof SyntaxError) {
validCode = 0;
console.warn(e.message);
}
} finally {
if(validCode){
"do some magic"
}
}
This Below code posted by go-oleg thanks to him
This code validate the correct syntax otherwise return error
Note:code is not vaildate run time error because it uses ast parser to analyze the correct syntax.
To Install
npm install esprima --save
code:
var esprima = require('esprima');
var userStringToTest = 'var a = 50;';
var isValid = isValidJs(userStringToTest);
if(isValid) {
alert('its validated!');
}
else {
console.log('its NOT valid syntax!');
}
function isValidJs(testString) {
var isValid = true;
try {
esprima.parse(testString);
}
catch(e) {
isValid = false;
}
return isValid;
}
put your desired value for b
//b="4+6";
try { eval(b); }
catch (err) {
if (err instanceof SyntaxError)
document.getElementById('screen').innerHTML = "<i>Syntax Error</i>";
/*In html make a div and put id "screen" in it for this to work
you can also replace this line with document.write or alert as per your wish*/
}
finally {
document.getElementById('screen').innerHTML = eval(b); //outputs answer
}