Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check ExceptionHandler if type conversion fails #988

Merged
merged 1 commit into from
Oct 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions Jint.Tests/Runtime/InteropTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2865,5 +2865,13 @@ static IEnumerable<string> MemberNameCreator(MemberInfo prop)
Assert.Equal((int) CustomNamedEnum.HeadersReceived, engine.Evaluate("o.jsEnumProperty").AsNumber());
}

[Fact]
public void ShouldBeAbleToHandleInvalidClrConversionViaCatchClrExceptions()
{
var engine = new Engine(cfg => cfg.CatchClrExceptions());
engine.SetValue("a", new Person());
var ex = Assert.Throws<JavaScriptException>(() => engine.Execute("a.age = \"It won't work, but it's normal\""));
Assert.Equal("Input string was not in a correct format.", ex.Message);
}
}
}
2 changes: 1 addition & 1 deletion Jint/Runtime/ExceptionHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ public static void ThrowMeaningfulException(Engine engine, TargetInvocationExcep
}

[DoesNotReturn]
private static void ThrowError(Engine engine, string message)
internal static void ThrowError(Engine engine, string message)
{
throw new JavaScriptException(engine.Realm.Intrinsics.Error, message);
}
Expand Down
15 changes: 14 additions & 1 deletion Jint/Runtime/Interop/DefaultTypeConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,20 @@ public virtual object Convert(object value, Type type, IFormatProvider formatPro
}
}

return System.Convert.ChangeType(value, type, formatProvider);
try
{
return System.Convert.ChangeType(value, type, formatProvider);
}
catch (Exception e)
{
if (!_engine.Options.Interop.ExceptionHandler(e))
{
throw;
}

ExceptionHelper.ThrowError(_engine, e.Message);
return null;
}
}

public virtual bool TryConvert(object value, Type type, IFormatProvider formatProvider, out object converted)
Expand Down