I am currently using rhyno javascript library and I notice the following issue while using try catch blcok.
Below is my sample code.
function main() {
var a =0;
try {
throw someException;
} catch (exception) {
var e = exception.name;
var error = exception;
return "Error is :"+error;
}
while debugging the code somehow the variable called exception declared inside catch is shown as undefined.But when I try to run the same code the exception is getting printed properly. Only issue I am seeing is while debugging the code.
Rhino optimizes away the local variable exception when it is unreferenced. So in the debugger, it won't be defined unless you use it. The workaround I usually use is similar to the one you do:
try {
doIt();
} catch (e) {
var ex = e;
// Now the value can be examined, because the assignment to a local variable causes the engine to require the variable in the scope
debugger;
}
This sort of thing can happen in Chrome DevTools also, for example, when a variable is not actually accessed inside a scope.
Related
If I receive an error from a framework or an error from the browser. Basically a runtime error of any kind. Without modifying the framework, is it possible for me to override the console logs that these frameworks make and the browser's errors. I want to use my own framework with own error handling system when informing the user of errors of practically anything runtime (not syntax errors). I don't know if you would class it all as runtime errors because of the way javascript is executed in the browser but hopefully you will get me?
Is this possible if all the frameworks are written in Javascript?
How is this achieved?
What considerations do I have to make between different browsers?
Thanks
You are probably looking for a try-catch block:
try {
alert(foo);
} catch(e) {
alert('The code got the following error: '+e.message);
}
Whenever the code between the try {} receives an error, the catch(e) {} block will execute, with the argument e being the error object for the error that occurred. In this case, the variable foo is not defined, so executing this code will result in an alert message saying "The code got the following error: foo is not defined"
While not over-riding console.log, you may be achieve the same effect by overriding window.onerror.
From the MDN documentation
window.onerror = function myErrorHandler(errorMsg, url, lineNumber) {
// Log the error here -- perhaps using an AJAX call
}
You could try overriding the console.log() function.
//Save original reference
var originalConsole = console;
//Override
console = {};
console.log = function()
{
//According to MDN the console.log function can receive a variable number of params
for(var i=0; i<arguments.length; i++)
{
//Make your changes here, then call the original console.log function
originalConsole.log("Change something: "+arguments[i]);
}
//Or maybe do something here after parsing all the arguments
//...
}
console.log("one", "two");
JSFiddle here.
You can override the console logs by creating a "console" object and overriding it's .log() function:
var console = {};
console.log = function(){};
Some browsers require this to be added to the window object directly; so, for browser compatibility, also add:
window.console = console;
Additionally, you can override other console functions (e.g. console.info, console.warn and console.error) if you're using those too.
Also, consider reading this blog post from Udi Talias on overriding the console functions. Good and quick read!
You can custom your console.log here
// copy the original
let originalConsole = Object.assign({}, console);
// do something with your log.
console.log = (value) => {
//some cool condition
if (true) {
value = "new_log : " + value
}
originalConsole.log(value);
};
I currently have a try/finally block of this format:
try {
var someOtherObject = new SomeOtherObject(param1, param2);
someOtherObject.doStuff();
// Object that basically holds a 'result set' of csv rows.
var csv = new CsvObject();
csv.openCSV(); // does not throw an error
do {
try {
// Code that grabs stuff from the csv in a straightforward fashion.
} catch (e) {
log.info(e); // Log the error and continue on.
}
} while (csv.hasNext());
} finally {
csv.closeFileCSV(); //throws a TypeError: Cannot call closeFileCSV() on undefined.
}
No errors are thrown in the loop, nor anywhere else that I can tell outside the finally block. Can anyone give me clues as to why it would throw a TypeError when calling closeFileCSV in the finally block? I'm not a javascript expert but it doesn't seem like scope should be a problem here. I know that csv gets initialized correctly, because the try block uses the object to do stuff and no errors are thrown.
I'm hoping I'm just not seeing something obvious. Let me know if more code needs to be pasted in order to solve this.
Thanks.
I've determined that the variable, someOtherObject, is returning a null object. So when the doStuff() method is called, an exception is thrown. However, the finally block is immediately fired once this exception happens; and inside the finally block, the TypeError is thrown because csv has not been initialized in the try block yet.
This latter error is the only one that gets shown however, which was the source of confusion. Once I resolved the issue with someOtherObject, the code worked. (I've also added guards around the close method to make sure that csv is initialized).
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
}