【问题标题】:Is it possible to catch an exception you can't handle (in C#)?是否可以捕获您无法处理的异常(在 C# 中)?
【发布时间】:2011-12-17 10:26:27
【问题描述】:

我有一个捕获 T 异常的泛型类:

公共抽象类 ErrorHandlingOperationInterceptor : OperationInterceptor where T : ApiException { 私有只读 Func _resultFactory; 受保护的 ErrorHandlingOperationInterceptor(Func resultFactory) { _resultFactory = 结果工厂; } 公共覆盖 Func> RewriteOperation(Func> operationBuilder) { 返回 () => { 尝试 { 返回操作生成器(); } 抓住(前) { var operationResult = _resultFactory(); operationResult.ResponseResource = new ApiErrorResource { Exception = ex }; 返回 operationResult.AsOutput(); } }; } }

带有特定异常的子类,例如

公共类 BadRequestOperationInterceptor : ErrorHandlingOperationInterceptor { 公共 BadRequestOperationInterceptor() : base(() => new OperationResult.BadRequest()) { } }

这一切似乎都很完美。但是,不知何故,在日志中(一次,而不是每次)是一个 InvalidCastException:

System.InvalidCastException:无法将“ErrorHandling.Exceptions.ApiException”类型的对象转换为“ErrorHandling.Exceptions.UnexpectedInternalServerErrorException”类型。 在 OperationModel.Interceptors.ErrorHandlingOperationInterceptor`1.c__DisplayClass2.b__1() 在 c:\BuildAgent\work\da77ba20595a9d4\src\OperationModel\Interceptors\ErrorHandlingOperationInterceptor.cs:line 28

第 28 行是关键。

我错过了什么?我做了什么傻事吗?

【问题讨论】:

  • 是不是因为被触发的异常不是 ApiErrorResource 的类型?什么类型的被抓到?
  • 嗯,总是有TruthException,因为你应付不了
  • 代码中哪一行是第28行?
  • @KierenJohnstone,你偷了我的评论!!
  • 在运行时,T 应该是一个特定的异常。那么它如何捕获 T 类型的异常,但又无法将其转换为 T 呢?

标签: c# generics error-handling


【解决方案1】:

正如 smithy 所说,您的 TApiErrorResource 类型。您在代码中的某些地方尝试使用不是从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 ();
}

【讨论】:

  • 其实我相信是ApiException的类型。
  • 我不明白这是如何回答这个问题的。类型系统不应该允许我认为您试图演示的问题 - 请注意通用约束where T : ApiException。 OP 的代码没有进行任何转换 - InvalidCastException 结果如何?
  • 这里给出的例子甚至没有调用可能有问题的方法,那么这究竟是如何引起问题的呢?
猜你喜欢
  • 2010-09-10
  • 2012-06-07
  • 1970-01-01
  • 2015-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
相关资源
最近更新 更多