Decorate error object from CLR #2278
-
|
Is it possible to add custom properties to the error object that gets caught in js? Let's say I want to make the following test pass. The idea is to send an "errorCode" property from the CLR. [TestClass]
public sealed class ScriptEngineExceptionTests
{
[TestMethod]
public void ErrorShouldContainProperties()
{
Engine engine = new(options =>
{
options.CatchClrExceptions();
});
engine.SetValue("myClass", new());
engine.Execute("""
function main () {
try {
myClass.MethodThatThrows();
} catch (e) {
return JSON.stringify(e);
}
}
""");
string result = engine.Invoke("main").ToString();
Assert.AreEqual("{errorCode:'InvalidOperation'}", result);
}
public class MyClass()
{
public void MethodThatThrows() => throw new InvalidOperationException("This is a test exception.");
}
}Right now the Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
|
This feature has landed main, now you can add decorator in options. #2280 |
Beta Was this translation helpful? Give feedback.
-
|
Thank you for the quick fix! Seems perfect, but while this is released, I also found a workaround, just in case someone else doesn't want to wait... Disabling ObjectInstance errorObject = engine.Intrinsics.Error.Construct(fullMessage);
errorObject.Set("message", fullMessage, throwOnError: false);
errorObject.Set("errorCode", errorCode, throwOnError: false);
throw new JavaScriptException(errorObject); |
Beta Was this translation helpful? Give feedback.
-
|
Oh, final question, @lahma. Is this the most optimal way to add a function to an JsValue toStringFunction = engine.Evaluate(
$$"""() => "Error ({{errorCode}}): {{fullMessage}}";""");
errorObject.Set("toString", toStringFunction, throwOnError: false);Thank you! |
Beta Was this translation helpful? Give feedback.
This feature has landed main, now you can add decorator in options. #2280