2011-10-28 38 views
6

我有捕捉的T異常的通用類:是否有可能捕捉到您無法處理的異常(在C#中)?

 
    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(); 
       } 
      }; 
     } 
    } 

隨着子類例如特定的異常

 
    public class BadRequestOperationInterceptor : ErrorHandlingOperationInterceptor<BadRequestException> 
    { 
     public BadRequestOperationInterceptor() : base(() => new OperationResult.BadRequest()) { } 
    } 

這一切似乎完美。但是,不知何故,在日誌中(一次,而不是每次)是一個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 

線28漁獲物。

我錯過了什麼?我做了一些真正愚蠢的事情嗎?

+7

嗯,總是有'TruthException',因爲你無法處理它 –

+0

代碼中的哪一行是第28行? –

+0

@KierenJohnstone,你偷了我的評論! –

回答

3

正如史密斯所說,你的TApiErrorResource類型。你是,在你的代碼中的某個地方,試圖創建ErrorHandlingOperationInterceptor,而Exception不是從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(); 
} 
+1

其實我相信它是'ApiException'類型。 – TrueWill

+0

我不明白這是如何回答這個問題。類型系統不應該允許我認爲你試圖演示的問題 - 注意通用約束'where T:ApiException'。 OP的代碼沒有進行任何轉換 - 「InvalidCastException」結果怎麼樣? –

+0

我想我應該說「有些地方ELSE在你的代碼」。 –