PDA

View Full Version : Throwing an error to abort javascript execution



jayapalchandran
11-10-2009, 06:40 AM
Hi,
I call a javascript function b from another function a.
in the function b at certain conditions i want to stop the javascript execution and i have did it by throwing an exception by using Throw New Error('Stopi').
It is working well.

Is it good to stop the execution of javascript abruptly.
Is it bad if the functions are not returned to the calling function and finally to the operating system.
I will there be a over flow of stack or will stack keep increasing if i am throwing many such errors.


Meanwhile IE shows the yellow exclamation icon in its status bar as usual that there is a javascript exception. When you click that you can see the error description as 'Stopi' which i have thrown.

Here is an example...

<input type='text' name='name' id='name' />


function validate()
{
isempty('name','Please enter your name');
// no if condition or return statement here
}

function isempty(src,msg)
{
var so = document.getElementById(src)
if(so.value=='')
{
alert(msg)
so.focus()
throw new Error('Stopi')
}
}

so i dont have to use if condition when validating. no braces, no return statement, and no need to call focus for every if condition so this code reduces 6 lines and multiplied by number of input controls you are going validate. so i just need to call isempty and if the control has empty value then the user will get an alert and the execution stops.

Please suggest.

jscheuer1
11-10-2009, 05:29 PM
An error is an error whether you created it or it just occurred. As such it will show up in any browser's error monitoring utility. IE is just (by default, it can be set by the user not to be) more obvious about this than others, but they all have ways and can be set to be as or more obvious about it than IE is.

It's really not all that much more code to do it correctly, even with strict indents and bracing:


function validate(){
if(isempty('name','Please enter your name')){
return;
}
}

function isempty(src,msg){
var so = document.getElementById(src);
if(so.value==''){
alert(msg);
so.focus();
return true;
}
return false;
}

If you are validating a bunch of fields:


function validate(){
var fields = [['name', 'name'], ['phonenumber', 'phone number'], ['address', 'address']];
for(var i = 0; i < fileds.length; ++i){
if(isempty(fields[i][0], 'Please enter your ' + fields[i][1])){
return;
}
}
}

function isempty(src,msg){
var so = document.getElementById(src);
if(so.value==''){
alert(msg);
so.focus();
return true;
}
return false;
}

jayapalchandran
05-05-2011, 09:13 PM
and i am finally sticking to this.

http://vikku.info/codesnippets/javascript/forcing-javascript-to-abort-stop-javascript-execution-at-any-time/

jscheuer1
05-06-2011, 12:51 AM
In my opinion that's silly. Why force an error when all you want to do is exit a loop? All loops should be inside functions anyway so as to not pollute the global scope with their i (or whatever) enumeration variables they use. So once you return from the function that the loop is in, you can take that value to return from any parent and/or calling function.

However, if you really feel a need to do it this way, there is a way to turn off the error reporting:


onerror = function(){return true;};

Try it out:


onerror = function(){return true;};

function javascript_abort()
{
throw new Error('This is not an error. This is just to abort javascript');
}

for(var i=0;i<10;i++)
{
if(i==5)javascript_abort();
alert(i);
}

No little yellow triangle in IE, and the Firefox error console will not report it either.

But, like the little boy cried "Wolf!", if later there's a real error, the browser will be of much less help in discovering it. IE 8's script console will show it, but nothing in Firefox's. And, as I say, nothing in IE's status bar.

Doing it like so:


function javascript_abort()
{
setTimeout(function(){onerror = function(){return false;};}, 0);
onerror = function(){return true;};
throw new Error('This is not an error. This is just to abort javascript');
}

for(var i=0;i<10;i++)
{
if(i==5)javascript_abort();
alert(i);
}

also avoids the error report in IE's status bar, and restores normal error reporting for both IE and Firefox afterward.

jayapalchandran
05-06-2011, 09:37 AM
Thank you for your response.

I will expriment it but before that i wanted to ask this.

if the current execution is deep inside a nested function and during that time if i want just stop the flow of execution then throw error would still help isn't it?

jscheuer1
05-06-2011, 01:51 PM
I believe so, try it.

By way of explanation, all my addition does is prevent normal error reporting for the custom error, everything else is the same.

That means, assuming a default setup, IE will no longer give that yellow error triangle in its status bar (IE 8 and less, as of IE 9 - IE no longer does that by default). It also means that in Firefox, if the error console is active, no error will appear in it.

In the last example from my last post it also restores normal error reporting for anything that happens later. This can be very helpful in diagnosing any real errors in the rest of code for the page.

Works fine here:


<!DOCTYPE html>
<html>
<head>
<title>Exit W/Custom Error - no error triangle IE/no error console Firefox</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function javascript_abort()
{
setTimeout(function(){onerror = function(){return false;};}, 0); // <-- sets a slight delay and then restores normal error reporting
onerror = function(){return true;}; // <-- prevents some error reporting in some browsers - the ones and the kinds we want to prevent
throw new Error('This is not an error. This is just to abort javascript');
}
function tryit()
{
for(var i = 0; i < 10; i++)
{
if(i === 5){javascript_abort();}
alert(i);
}
alert('still running'); // <-- never fires
}
</script>
</head>
<body>
<h2>Exit With Custom Error</h2>
<div>Gives no error triangle in IE and no error console entry in Firefox. Restores normal error reporting afterward.</div>
<div>&nbsp;</div>
<input type="button" value="Try It" onclick="tryit();">
<div>&nbsp;</div>
<input type="button" value="Real Error" onclick="not_a_defined_function();">
<div>After trying out the "Try It" button, you can use the "Real Error" Button to see that normal error reporting has been restored.</div>
<span>Be aware though, once you get the yellow triangle in IE's status bar or the red circle X in Firefox error console, they will not go away until you refresh the page.</span>
<div>This is the normal behavior in those browsers.</div>
</body>
</html>

jayapalchandran
05-06-2011, 04:36 PM
I will get back here after experiments. And i really thank you for the effort. I will be back.