Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do not stop JavaScript when it throws an exception

I am writing a Windows Sidebar Gadget using JavaScript. Now I would like to have all JavaScript exceptions caught and logged to a text file. One problem is that when an exception is thrown at any line, the next line will not be executed. Is it possible to catch exceptions automatically so that the following line of JavaScript can be executed.

Here is the sample code which demonstrates my problem:

try
{
    alert(document.getElementById("non-existing-element").value);
}
catch(ex)
{
}
alert("This is shown.");
alert(document.getElementById("non-existing-element").value);
alert("This is not shown.");

So one big try-catch-method whould allow to log the error but the rest of the code would not be executed. One solution would be to catch errors for every line. But would be too much code for several thousand lines. (or I write a macro which does this for me) Maybe anyone can help me.

Thank you.

like image 643
1' OR 1 -- Avatar asked Dec 13 '22 10:12

1' OR 1 --


1 Answers

Instead of trying to catch errors, you should be trying to build proper logic to control them.

var myEle = document.getElementById("non-existing-element")

if (myEle != null)
   alert(dmyEle.value);

But you are describing suppressing errors

You can suppress error in JavaScript with a onerror event handler.

function handleErr(msg, url, line_no){ 
   var errorMsg = "Error: " + msg + "\n"; 
       errorMsg += "URL: " + url + "\n"; 
       errorMsg += "Line: " + line_no + "\n\n"; 

    alert(errorMsg); 

 return true;
} 

// Set the global onerror; 
onerror = handleErr;

More information here

like image 73
Utilitron Avatar answered Dec 22 '22 00:12

Utilitron