仅在Release中尝试捕获的更好方法?

Luk*_* Vo 2 c# asp.net exception try-catch

当我想调试引发异常的应用程序时,这意味着我需要禁用try-catch块,如下所示:

#if !DEBUG
                try
                {
#endif
                    // Do something
#if !DEBUG
                }
                catch (ArgumentException)
                {
                    Console.WriteLine("Something wrong");
                }
#endif
Run Code Online (Sandbox Code Playgroud)

注意:我知道有关Visual Studio的已处理异常的中断,但是缺点是它会在相同类型的每个异常处中断。编辑以重新表达我的意思:例如,函数A和B都抛出NullReferenceException,但是我只想检查A何时抛出了NullReferenceException,而不是B(检查B中的NulRefExc已正确)。

有人可能会问我为什么需要那个。通常我运行ASP.NET MVC代码时不进行调试(但仍在具有DEBUG变量的Debug构建中),并且抛出异常确实非常好,而不是捕获异常(当然,仅在开发模式下),因为带有堆栈跟踪的错误页面将会显示出来,因此我们可以更快地跟踪错误。

有没有更干净的方法来编写上层代码?

Dmi*_*rov 7

从C#6开始,您还可以为此使用异常过滤器

try
{
    // Do something
}
catch (ArgumentException) when (!Env.Debugging)
{
    // Handle the exception
}
Run Code Online (Sandbox Code Playgroud)

Env.Debugging某处定义为

public static class Env
{
#if DEBUG
    public static readonly bool Debugging = true;
#else
    public static readonly bool Debugging = false;
#endif
}
Run Code Online (Sandbox Code Playgroud)

另外,如果未捕获到异常对象(由于when测试失败,即在调试中),您将在异常对象中获得原始调用堆栈。对于重新抛出的异常,您将必须提供原始异常作为内部异常,并付出额外的努力来处理它。

这种方法还允许基于其他条件来启用/禁用异常处理web.config,例如,该设置将使您无需重新编译即可轻松处理:

public static class Env
{
    public static readonly bool Debugging =
      Convert.ToBoolean(WebConfigurationManager.AppSettings["Debugging"]);
}
Run Code Online (Sandbox Code Playgroud)

  • 对于 .NET Core,您可以使用: `catch (Exception ex) when (!_hostingEnvironment.IsDevelopment())` 并在构造函数中注入 `IHostingEnvironment`。 (3认同)