zzzprojects / Eval-Expression.NET

C# Eval Expression | Evaluate, Compile, and Execute C# code and expression at runtime.
https://eval-expression.net/
Other
449 stars 86 forks source link

Can I not throw an exception when expression evaluation fails? #137

Closed saber-wang closed 2 years ago

saber-wang commented 2 years ago

for example:

Eval.Execute<bool?>("test==\"124\"", new {})

The following exception will be thrown:

Unhandled exception. Z.Expressions.Compiler.Shared.EvalException: Oops! The current expression is null. The error occurred for expression "test" at position 0 near "test==\"124\"".
   at  . (ExpressionScope , SyntaxNode , Func`3 )
   at  . (ExpressionScope , SyntaxNode , Expression , Boolean )
   at  . (ExpressionScope , SyntaxNode , Expression , Boolean )
   at  . (ExpressionScope , SyntaxNode , Expression , Boolean )
   at  . [ ](EvalContext , String , IDictionary`2 , Type , EvalCompilerParameterKind , ExpressionScope , String , Boolean , Boolean)
   at  . [ ](EvalContext , String , IDictionary`2 , Type , EvalCompilerParameterKind , Boolean , Boolean , Boolean )
   at Z.Expressions.EvalContext.Execute[TResult](String code, Object[] parameters)

I want to return default.

JonathanMagnan commented 2 years ago

Hello @saber-wang ,

Thank you for asking,

I can understand the reason when using a nullable type such as bool?.

Are you looking for a solution only for when the compilation fails (like this case) or also when the execution fails?

Best Regards,

Jon

saber-wang commented 2 years ago

@JonathanMagnan Thank you for your answer. After reading your answer, I realized that the compilation phase failed. Can I handle it at this stage?

JonathanMagnan commented 2 years ago

Hello @saber-wang ,

It depends on what you mean by "Can I handle it". What exactly do you want to do?

You can sure handle it with a try/catch but I'm not really sure what you are looking for.

When the compilation fail, the error causing it is raised, and the 2 followings properties are populated:

saber-wang commented 2 years ago

@JonathanMagnan I don't want to throw an exception here because the object is dynamic.😁

JonathanMagnan commented 2 years ago

Hello @saber-wang ,

Your current example is an anonymous type, not an expando / dynamic object.

Expando and dynamic object will normally compile without problem but will indeed raise an error when executing if, for example the property in the expression doesn't exists.

saber-wang commented 2 years ago

@JonathanMagnan That's right. I was negligent. Thanks for your help.