gra*_*hay 6 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行是捕获.
我错过了什么?我做过一些非常愚蠢的事吗?
正如铁匠所说,你的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 ();
}
Run Code Online (Sandbox Code Playgroud)