gpt4 book ai didi

c# - 嵌套尝试/捕捉

转载 作者:IT王子 更新时间:2023-10-29 04:49:20 28 4
gpt4 key购买 nike

嵌套的 Try/Catch 是否表示您的编码不干净?我想知道,因为在我的 catch 中,我正在调用另一个方法,如果失败,我会收到另一个运行时错误,所以我很想再次使用另一个 try/catch 将这些调用包装在 catch 中。我想知道这样做是否正常?

例如

    catch (Exception ex)
{
transaction.VoidOrder(transactionID);

LogError(ex.ToString());
Response.Redirect("Checkout", false);
}

所以 VoidOrder 甚至 LogError 方法都可能被炸毁。现在,当我调用 VoidOrder 时,我在 transactionID 上得到一个 null ref,因为它调用了一个 BL 方法,并且在该 BL 方法中我重新抛出以便我可以捕获它在上面代码的这个更高级别。但是,如果我再次在 catch 区内 throw ,那么我也需要接住它。

最佳答案

以下是我们解决问题的方法:

从 UI/代码隐藏级别到其他层的所有调用都使用 try-catch,我们总是在其中捕获自定义异常。底层采取的所有操作都有自己的 try-catch,它记录、包装和抛出自定义异常。然后,UI 可以依赖于此并使用友好的错误消息查找已处理的异常。

代码隐藏:

protected void btnSubmit_Click(object sender, EventArgs e)
{
//do something when a button is clicked...
try
{
MyBL.TakeAction()
}
catch(MyApplicationCustomException ex)
{
//display something to the user, etc.
ltlErrorPane.Text = ex.Message;

//or redirect if desired
if(ex.ErrorType == MyCustomErrorsType.Transactional)
{
Response.Redirect("~/Errors/Transaction.aspx");
}
}
}

BL:

在业务层,任何可能失败的操作都使用 try-catch,在将问题抛给 UI 之前记录并包装问题。

public class MyBL
{
public static void TakeAction()
{
try
{
//do something
}
catch(SpecificDotNetException ex)
{
//log, wrap and throw
MyExceptionManagement.LogException(ex)
throw new MyApplicationCustomException(ex, "Some friendly error message", MyCustomErrorsType.Transactional);
}
finally
{
//clean up...
}
}
}

异常处理程序:

实际的异常处理程序有多种记录方式,包括事件日志、文件日志和最后的电子邮件(如果所有其他方法都失败了)。如果记录器不能执行任何预期的操作,我们选择简单地返回 false。 IMO 这是个人选择。我们认为 3 种方法连续失败的可能性(事件日志失败、尝试文件日志、失败、尝试电子邮件、失败)的可能性很小。在这种情况下,我们选择允许应用程序继续运行。您的另一种选择是允许应用程序完全失败。

public static class MyExceptionManagement
{
public static bool LogException(Exception ex)
{
try
{
//try logging to a log source by priority,
//if it fails with all sources, return false as a last resort
//we choose not to let logging issues interfere with user experience

//if logging worked
return true;
}
catch(Exception ex)
{
//in most cases, using try-catch as a true-false is bad practice
//but when logging an exception causes an exception itself, we do
//use this as a well-considered choice.
return false;
}
}
}

最后,作为故障保险,我们实现了 Application_Error 全局事件处理程序(在 Global.asax 中)。对于我们没有正确 try catch 某些东西的情况,这是最后的手段。我们通常记录并重定向到一个友好的错误页面。如果上述自定义错误处理成功完成,则很少有错误会进入全局处理程序。

希望对您有所帮助。这是一种可能的解决方案。多年来,它在一些较大的应用程序上对我们来说效果很好。

关于c# - 嵌套尝试/捕捉,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2313696/

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