How to access the property/field Exception.ErrorDetails after an exception occurred?

Viewed 113

I want to be able to get access to e.ErrorDetails contents when an exception occurs in a try/catch block, but unfortunately I can't.

How could I do this without parsing the entire exception object?

try
{...}
catch (Exception e)
{Console.WriteLine(e.ErrorDetails);} //compile error!

Thank you

enter image description here

1 Answers

You need to have an expression of type IScriptEngineException. The simplest approach to that is probably to catch that specific exception. You can't use the interface for that directly, but you can use an exception filter to have the same effect as if you wrote catch (IScriptEngineException ex):

try
{
    // ...
}
catch (Exception e) when (e is IScriptEngineException ex)
{
    Console.WriteLine(ex.ErrorDetails);
}
// Potentially a more general catch block here

You should consider carefully whether you want to have a more general catch block (catching all exceptions) - without more context, we can't give much advice for that. "Catch all" blocks are generally appropriate only at the top level of a program - e.g. to avoid taking a server down when a single request fails, or to give diagnostic information in a console app before exiting.

Related