我有一个通用类,可以捕获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(); } }; } }
还有特定异常的子类:
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行是catch语句。
我错过了什么?我做了什么很愚蠢的事情吗?