Jeremy Miller Jeremy Miller - 4 months ago 27
AngularJS Question

Angular 2 with Typescript expression evaluation is throwing error and not recovering

I was writing an expression builder which evaluates an line of code and then lets me know if it is valid or not

e.g.

x = 3
y = 5


expression =
if x == 3 && y > 6 then


HTML template code:

<div class="form-group">
<label for="ifThenExpression">If Then Expression</label>
<input type="text" class="form-control" [(ngModel)]="ifThenExpression" id="ifThenExpression" placeholder="if x == y then">
</div>


So the main coding I have in in a Typescript file


  1. I want to "handle errors" better

  2. I wish to not throw an exception in which the browser does not recover from unless I refresh.



Code

import { Component } from '@angular/core';
@Component({
selector: 'eval-app',
templateUrl: 'app/evals/eval.form.component.html'
})
export class AppEvalComponent {
ifThenExpression: string;
variableX: string;
variableY: string;
result: string;
pageTitle: string = 'Evaluate Expression';


isIfStatement(statement: string) {
var pattern = new RegExp('(if)*.*(then)');
return pattern.test(statement);
}

evaluateExpression(): void {
console.log('Click Worked');
if (this.isIfStatement(this.ifThenExpression)) {
var token = this.ifThenExpression.replace('if', '').replace('then', '').replace('x', this.variableX).replace('y', this.variableY).trim();
this.result = eval(token);
console.log(this.ifThenExpression);
}
else {
this.result = 'Invalid Expression';
}

console.log(this.result);
}
}


So if the expression has a variable it does not like, too many conditions, missing the "then" random other characters , It just decides to not hit the ELSE, but "blow up"

e.g.
EXCEPTION: Error in app/evals/eval.form.component.html:16:54
eval code (92) (1900,17)


ORIGINAL STACKTRACE:
eval code (92) (1900,17)


and so much more.

Answer

Other than the fact that you need to add a lot more conditionals to make this a decent expression engine, a try /catch will work for your issue.

This will work for Angular2 / Typescript

evaluateExpression(): void {
  try 
  {
    console.log('Click Worked');

    if (this.isIfStatement(this.ifThenExpression)) {
        var token = this.ifThenExpression.replace('if', '').replace('then', '').replace('x', this.variableX).replace('y', this.variableY).trim();
        this.result = eval(token);
        console.log("this.ifThenExpression = " + this.ifThenExpression);
    }
    else {
        this.result = 'Invalid Expression';
    }

       console.log(this.result);
  } catch (error) {
       // generic catch all errors and spit them out
       console.log("error");   
  }

}
Comments