I have two projects. In one of them I use MailKit and it is responsible for all kinds of email.
Here I could get SmtpCommandExceptions
or SmtpProtocolExceptions
that are derived of CommandException
which is derived of the normal System.Exception
.
I want to give the exception to the other project without binding the complete MailKit into the other project. So I thought about getting the additional properties into strings, putting them together and send everything else back.
Is there any way of extracting the exception out of the derived class and throw away all additional methods, properties, and so on?
The typical way to deal with this kind of problem is to wrap the exception in a custom exception class:
public class MyWrappedException : Exception
{
public string MyProperty { get; }
public MyWrappedException(string message, string myProperty, Exception innerException)
: base(message, innerException)
{
MyProperty = myProperty;
}
}
Called like:
try
{
DoSomething();
}
catch(InvalidOperationException ex)
{
throw new MyWrappedException("Oups", "tried doing X", ex);
}
This keeps the all the original exception information, but most of it will not be visible unless you use a debugger or it is included when converting to a string. You can select what properties you want to include in the wrapper. This lets you catch your wrapped exception without an direct dependency on mailkit.