I have a generic class that catches exceptions from T:
public abstract class ErrorHandlingOperationInterceptor <T>: OperationInterceptor where T: ApiException
{
private readonly Func <OperationResult> _resultFactory;
protected ErrorHandlingOperationInterceptor (Func <OperationResult> resultFactory)
{
_resultFactory = resultFactory;
}
public override Func <IEnumerable <OutputMember>> RewriteOperation (Func <IEnumerable <OutputMember>> operationBuilder)
{
return () =>
{
try
{
return operationBuilder ();
}
catch (T ex)
{
var operationResult = _resultFactory ();
operationResult.ResponseResource = new ApiErrorResource {Exception = ex};
return operationResult.AsOutput ();
}
};
}
}
With subclasses for specific exceptions, e.g.
public class BadRequestOperationInterceptor: ErrorHandlingOperationInterceptor <BadRequestException>
{
public BadRequestOperationInterceptor (): base (() => new OperationResult.BadRequest ()) {}
}
It all works great. But, somehow, in the logs (once, not every time) this is an InvalidCastException:
System.InvalidCastException: Unable to cast object of type 'ErrorHandling.Exceptions.ApiException' to type 'ErrorHandling.Exceptions.UnexpectedInternalServerErrorException'.
at OperationModel.Interceptors.ErrorHandlingOperationInterceptor`1.c__DisplayClass2.b__1 () in c: \ BuildAgent \ work \ da77ba20595a9d4 \ src \ OperationModel \ Interceptors \ ErrorHandlingOperationInterceptor.cs: line 28
Line 28 is the catch.
What am I missing? Did I do something really dumb?
source share