我有一个捕获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行是捕获。
我错过了什么?我做过一些非常愚蠢的事吗?
答案 0 :(得分:3)
史密斯说,你的T
类型为ApiErrorResource
。您在代码中的某些位置尝试使用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}}