grahamrhay
grahamrhay

Reputation: 2166

Is it possible to catch an exception you can't handle (in C#)?

I have a generic class that catches exceptions of 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()) { }
    }

This all seems to work perfectly. But, somehow, in the logs (once, not every time) 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? Have I done something really dumb?

Upvotes: 5

Views: 325

Answers (1)

Erik Philips
Erik Philips

Reputation: 54618

As smithy said, your T is of type ApiErrorResource. You are, some where in your code, attempting to create your ErrorHandlingOperationInterceptor with an Exception that is NOT derived from ApiErrorResource.

try
{
// throw Exception of some sort
}
catch (BadRequestException ex)
{
    BadRequestOperationInterceptor broi = new BadRequestOperationInterceptor ();
}
catch (Exception ex)
{
    // this is NOT right
    BadRequestOperationInterceptor broi = new BadRequestOperationInterceptor ();
}

Upvotes: 2

Related Questions