是否可以捕获无法处理的异常(在C#中)?

时间:2011-10-28 16:21:10

标签: c# generics error-handling

我有一个捕获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行是捕获。

我错过了什么?我做过一些非常愚蠢的事吗?

1 个答案:

答案 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}}