2011-10-28 30 views
6

Tôi có một lớp chung mà bắt ngoại lệ của T:Có thể bắt ngoại lệ mà bạn không thể xử lý (trong C#) không?

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

Với lớp con cho ngoại lệ cụ thể ví dụ

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

Điều này dường như hoạt động hoàn hảo. Nhưng, bằng cách nào đó, trong nhật ký (một lần, không phải mọi lần) là một 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 

Dòng 28 là bắt.

Tôi đang thiếu gì? Tôi đã làm một cái gì đó thực sự câm?

+7

Vâng, luôn có 'TruthException', bởi vì bạn không thể xử lý nó –

+0

Dòng nào trong mã là dòng 28? –

+0

@KierenJohnstone, bạn đã đánh cắp nhận xét của tôi !! –

Trả lời

3

Khi thợ rèn nói, số T của bạn thuộc loại ApiErrorResource. Bạn, một số nơi trong mã của bạn, đang cố gắng tạo ErrorHandlingOperationInterceptor của bạn với một số Exception không được bắt nguồn từ 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

Thực ra tôi tin rằng đó là loại 'ApiException'. – TrueWill

+0

Tôi không hiểu cách này trả lời câu hỏi. Hệ thống kiểu không nên cho phép vấn đề mà tôi nghĩ bạn đang cố gắng chứng minh - lưu ý ràng buộc chung 'trong đó T: ApiException'. Mã OP không thực hiện bất kỳ phép đúc nào - kết quả 'InvalidCastException' có thể như thế nào? –

+0

Tôi đoán tôi nên nói "một số nơi ELSE trong mã của bạn". –

Các vấn đề liên quan