gpt4 book ai didi

c# - 如何连接两个异常?

转载 作者:太空狗 更新时间:2023-10-29 18:16:33 24 4
gpt4 key购买 nike

我有以下一段代码用于处理我的网络应用程序中的异常:

application.Response.Clear();
application.Response.Status = Constants.HttpServerError;
application.Response.TrySkipIisCustomErrors = true;

LogApplicationException(application.Response, exception);
try
{
WriteViewResponse(exception);
}
// now we're in trouble. lets be as graceful as possible.
catch (Exception exceptionWritingView)
{
// Exception wrapper = ??
WriteGracefulResponse(exceptionWritingView);
}
finally
{
application.Server.ClearError();
}

这里的问题是,如果在尝试将响应呈现为 ViewResult 时出现异常,我将“抑制”原始异常(无论如何在 View 中) ),并仅显示导致错误 ViewResult 抛出的原因。

我想同时使用 exceptionexceptionWritingView 并为两者创建一个异常(exception),exceptionWritingView 位于顶部。

这将是:

exceptionWritingView
-> inner exceptions of exceptionWritingView
-> original exception that raised the unhandled exception handler
-> its inner exceptions

但是我无法在我的 exception 对象上设置 InnerException 属性。那么我该如何实现呢?

在“最佳”情况下,我可以使用 new Exception(exceptionWritingView.Message, exception) 创建一个新的 Exception,但我会丢失部分 StackTrace 再加上我会丢失 exceptionWritingView 可能拥有的任何 InnerException

反射(reflection)是唯一的出路吗?用反射(reflection)去做会有那么可怕吗?

最佳答案

您可以使用 System.AggregateException .

例子:

WriteGracefulResponse(new AggregateException(new Exception[]
{
exceptionWritingView,
originalUnhandledException
}));

关于c# - 如何连接两个异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11919518/

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