Is it possible to catch an exception that you cannot handle (in C #)?

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?

+6
source share
1 answer

As the forge said, your T is of type ApiErrorResource . You are somewhere in your code trying 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 (); } 
+3
source

Source: https://habr.com/ru/post/900303/


All Articles