I'm making a calculator in Javascript for my school homework and it's using the function eval(). Yes, I know, eval is evil, but I can assure you that I already secured this, so there's no way of exploiting it.
The eval turns the value in textbox into an answer, which is then displayed in another textbox. However, when the syntaxe is wrong (for example, user enters "1++2") I would like if the script displayed some kind of error. But eval() just seems to disappear when the input is unvalid. It returns no value, no error (well, chrome tries explaining it with 'Uncaught Syntaxerror', but that is no use for me) so I have no way to explain to the script what to do, if user messes up the syntaxe.
TL;DR: How do I make the script display an error message, if the eval() has unvalid input?
Thanks in advance
It throws (raises) an exception, which you can catch (handle) and do whatever you want with:
var s;
try
{ s = eval('1++2'); }
catch(e)
{ s = e; }
// now s is either the result, or the exception-info
You should use a try catch block to gracefully show the user that an error has occured.
function evalJS(JsCode)
{
try
{
eval(JsCode);
}
catch(e)
{
alert('The string ' + JsCode + ' contained incorrect JS syntax.');
}
}
evalJS('bogus code');
Related
I know there are many other posts about this topic, but I still can't get it working.
I am using Angular 8 in my project and I want to send the browser console message to a server log file.
Could someone please clearifiy does questions for me:
When does the window.onerror get trigged? - right know I put the function within the constructor, is that ok so?
Does it get trigged, if I serve the project local?
window.onerror = function (errorMsg, url, lineNumber) {
alert(errorMsg + ' ' + lineNumber);
};
What do I have to do to get it triggered? (or does for example a thrown error of a missing certificate - trigger this function?)
console.error('test') - does this trigger it?
throw new Error() - or this?
Does Console-Errors like CORS will trigger this function?
I also read that it would get triggered if an img or script source is not avilable.
app.compentent.html: <img src="test.png">
app.copmentent.ts in the constructor (the code of point one)
But I still don't get the alert to display.
I am grateful for any help - thanks
The following may work for you. I used it in some Vue.js code to test triggering window.onerror(). Using eval() should allow you to bypass the compile-time checks of Angular and putting it in window.onload() will ensure it is evaluated after page load.
window.onerror = function (message, source, lineno, colno, error) {
alert('onerror called: ' + message);
}
window.onload = function () {
eval('undefined_function()');
}
As a security note, don't use eval() in production, especially if user input could get anywhere near it.
I've tried triggering error function with your code
window.onerror = function (errorMsg, url, lineNumber) {
alert(errorMsg + ' ' + lineNumber);
};
callingnonexistancefunction()
It is triggering while calling a non exist function.
Hope you'll get some reference
I was reading the book Professional Javascript For Web Developers, and saw the following code. I have some questions about it:
What does "throw new Error()" return? Undefined?
What will happen to the code block of "if" if there is an error thrown out?
function matchesSelector(element, selector){
if(element.matchesSelector){
return element.matchesSelector(selector);
}else if(element.msMatchesSelector){
return element.msMatchesSelector(selector);
}else if(element.mozMatchesSelector){
return element.mozMatchesSelector(selector);
}else if(element.webkitMatchesSelector){
return element.webkitMatchesSelector(selector);
}else{
throw new Error("Not supported!");
}
}
if(matchesSelector(document.body, "body.page1")){
//do somthing
}
When an error is thrown, if it is not caught using a try...catch block, the scope execution just stops.
Nothing is returned by that function, and if that function's return value is used somewhere in if statement, that if statement block is not executed as well.
This particular block of code is an attempt to create a generic, cross-platform selector. If you get to the error, then whatever browser you're on doesn't support any of the given selector matches (and may likely be considered a fringe browser, used by an "acceptably small" minority of users). It will fail, and an error message may be returned in the console. But it will most likely die silently.
By extension, when the final if() is run, it'll also die silently...
I'm writing an assembler and simulator for a toy assembly language that I have my CS students use in class. I'm writing it in javascript with the idea that I could then build a simple UI in the browser which would show students how each instruction changes the state of the machine and such.
One question that I'm grappling with is the best way to return error information from the assembler when invalid assembly code is passed. The assembler has an extremely simple API at the moment:
var assembler = ... // Get the assembler object
var valid_source = "0 mov r1 r2\n1 halt";
var valid_binary = assembler.assemble(valid_source); // String containing 0's and 1's
var invalid_source = "foo bar baz!";
var invalid_binary = assembler.assemble(invalid_source); // What should happen here?
I have a few thoughts about how this might work:
Construct and throw a new javascript Error object. This seems like overkill (and ultimately maybe not even helpful since the user wouldn't care about the javascript stacktrace, etc).
Return a string or object containing error information. Then the user of the assembler gets to make the choice about what to do with errors (if anything).
Change the assembler API to use a callback instead:
assembler.assemble(source, function(binary, error) {
if (error) {
// Handle the error
}
// Otherwise, do stuff with the binary
});
Something else entirely?
Any ideas, thoughts, or feedback would be much appreciated.
I think your three options would work fine. Now from my perspective:
I would keep away from the third option because it gives the feeling it is an async function when it is not.
I would go for option 1 or 2. The first one is a little overkill but I think it is the most realistic approach to what compilers do. Exit with no zero code. But then you would need to add a try/catch block to handle the error.
So the next option is to return an error object. Seems the best option for me.
I recommend you to return an Error object. It is as simple as:
return new Error('Parsing error');
// Or with an error name
var error = new Error('Parsing error');
error.name = 'PARSING_ERROR';
return error;
One advantage to use the error object is that it gives you the stack trace and other handy stuff. More info here.
Also, to check if there was any error just need to check the variable type:
if (typeof valid_binary === 'string') { /* no error */ }
// Or
if (typeof valid_binary === 'object') { /* error */ }
Good luck!
I want to be able to call a function within an if statement.
For example:
var photo = "yes";
if (photo=="yes") {
capturePhoto();
}
else {
//do nothing
};
This does nothing though. The function is clearly defined above this if statement.
Edit: Wow, downboated to hell! capturePhoto(); was just an example function that didn't really need any more explanation in this scenario?
That should work. Maybe capturePhoto() has a bug?
Insert an alert() or console.log():
var photo = "yes";
if (photo == "yes") {
alert("Thank you StackOverflow, you're a very big gift for all programmers!");
capturePhoto();
} else {
alert("StackOverflow.com must help me!");
}
I'm not seeing any problems here. I used this code and the function call worked. I kept your code and just added a function called capturePhoto().
Are you sure that the code you're using to call the function is firing?
var photo = "yes";
if (photo=="yes")
{
capturePhoto();
}
else
{
//do nothing
};
function capturePhoto()
{
alert("Pop up Message");
}
You probably missed something, a quotation, a semicolon or something like that. I would recommend you to use a debugger like Firebug or even Google Chrome's Web Developer Tool. You will know what's wrong with your code and where it is wrong.
You may take a look at this live code that your code above works: http://jsfiddle.net/ZHbqK/
The code looks fine to me (except you don't need the ; at the end of the last line). Check your error log; perhaps the browser thinks capturePhoto is not defined for some reason. You can also add alert statements to make sure the code is actually running:
var photo = "yes";
alert('Entering if statement');
if (photo=="yes") {
alert('then');
capturePhoto();
} else {
alert('else');
//do nothing
}
When you encounter a situation where it seems like a fundamental language feature is not working, get some more information about what is going on. It is almost never the platform's fault. It is occasionally a misunderstanding of how the feature works (e.g. why does parseInt('031') == 25 ?). It is usually a violation of an assumption you're making about the code that isn't holding up because of a problem elsewhere.
You should also consider using true and false instead of strings that could be manipulated depending on input.
If I had to correct the following code, then I should've done it like this;
var photo = true; // Will capture picture.
if (photo) { // 'true' is a truthy value.
capturePhoto();
} else {
// Do nothing
}
The code that you posted does work.
I copied it and tested it.
Demo: http://jsfiddle.net/Guffa/vraPQ/
The only thing wrong with it that I can see is a semicolon after the closing bracket, but that is only a style problem. It will form an extra empty statement, but that doesn't cause any problems.
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
}