gpt4 book ai didi

c# - 是否有可能捕获您无法处理的异常(在 C# 中)?

转载 作者:太空狗 更新时间:2023-10-29 21:55:22 25 4
gpt4 key购买 nike

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

我错过了什么?我是不是做了什么蠢事?

最佳答案

正如史密斯所说,您的 TApiErrorResource 类型。你在你的代码中的某个地方试图创建你的 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 ();
}

关于c# - 是否有可能捕获您无法处理的异常(在 C# 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7931996/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com