Reputation: 4760
Let's say I have this code:
var myVar = 0;
function myFunctionOne() {
myVar = myVar + 2;
if(myVar <= 3) {
alert("all is good");
} else {
showError(myVar);
}
}
function myFunctionTwo() {
myVar = myVar + 2;
if(myVar <= 3) {
alert("all is good");
} else {
showError(myVar);
}
}
function myFunctionThree() {
//This should never run....
myVar = myVar + 2;
if(myVar <= 3) {
alert("all is good");
} else {
showError(myVar);
}
}
function showError(myVar) {
alert("Error Var is larger than 3. Var is" + myVar);
return false;
//This doesn't seem to stop anything
}
myFunctionOne();
myFunctionTwo();
myFunctionThree();
Here is also the fiddle: http://jsfiddle.net/dzjk44Lr/
What can I put inside my showError() function, that will kill any subsequent function calls? In this example, myFunctionThree(); should never run.
I know this is a simple example, but I'm trying to get my head around the module pattern, and in my module I have a lot of functions that delegate work, and modify variables. So if one function fails, or is given an illegal variable, I want everything to stop and show the user an error. Because if there was an error in myFunctionOne() for example, there is no point in continuing to execute any of the other code.
I guess, I'm looking for something like the php exit() function. Any advice about how to do this, or how I should do it differently would be greatly appreciated.
Upvotes: 0
Views: 8391
Reputation: 1451
You can use javascript throw statement.
According to Mozilla MDN
Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
Example:
throw "An error ocurred."
You can also go pro and throw an error object like this:
throw new MyAppError("custom error str", 128);
Upvotes: 1
Reputation: 816262
You can throw an error:
throw new Error("Error Var is larger than 3. Var is" + myVar);
Upvotes: 3