在C#中,能否捕获无法处理的异常?

5
我有一个通用类,可以捕获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语句。

我错过了什么?我做了什么很愚蠢的事情吗?


是因为被触发的异常不是ApiErrorResource类型吗?当捕获到时,ex是什么类型? - Smithy
8
好的,总有“真相例外”,因为你无法处理它。 - Kieren Johnstone
1
@KierenJohnstone,你抄袭了我的评论!! - Doug Chamberlain
在运行时,T 应该是一个特定的异常。那么它如何能够捕获类型为 T 的异常,但却无法将其转换为 T 呢? - grahamrhay
这个想法是有嵌套的拦截器,每个拦截器只关心特定的异常。如果它无法处理,就会向上冒泡。 - grahamrhay
显示剩余5条评论
1个回答

2
正如smithy所说,你的 T 是类型为 ApiErrorResource 的。你在代码中的某个地方,试图使用一个未从 ApiErrorResource 派生的 Exception 创建你的 ErrorHandlingOperationInterceptor
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
我不理解这个回答如何解决问题。类型系统不应该允许出现我认为你想展示的问题 - 请注意泛型约束where T : ApiException。楼主的代码没有进行任何强制转换 - 怎么可能导致InvalidCastException呢? - default.kramer
这里给出的示例甚至没有调用可能存在问题的方法,那么这会导致什么问题呢? - Voo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接