【发布时间】:2018-11-21 22:51:15
【问题描述】:
在我的 asp.net 应用程序中,如果应用程序抛出异常,它会被捕获并提供 500 页。我想在抛出位置破坏调试器。目前我正在使用以下代码sn-p:
void ExceptionHandler(Exception ex) {
if (Debugger.IsAttached)
{
Debugger.Break();
}}
但是,此代码在ExceptionHandler 处中断,而不是在抛出位置处。如何在投掷地点打破?
我不想更改异常设置,因为我想中断到达 ExceptionHandler 的异常,而不是系统恢复的异常。
为了更好地说明我的问题:
class Server // Server owned by third party
{
static void Main(string[] args)
{
AppDomain.CurrentDomain.FirstChanceException += (source, e) =>
{
// This does not help, because there are legit exceptions
Console.WriteLine("FirstChanceException event raised in {0}: \"{1}\"",
AppDomain.CurrentDomain.FriendlyName, e.Exception.Message);
};
AppDomain.CurrentDomain.UnhandledException += (source, e) =>
{
// This does not help, because exception should be handled by server, otherwise it would shut down
Console.WriteLine("UnhandledException event raised in {0}: \"{1}\"",
AppDomain.CurrentDomain.FriendlyName, e.ExceptionObject);
};
var app = new Application();
while (true)
{
try
{
app.ProcessRequest();
}
catch (Exception e)
{
// If we get here this mean that something is wrong with application
// Let's break on line marked as #1
Console.WriteLine("Server swallowed an exception \"{0}\"", e.Message);
Debugger.Break(); // Debugger breaks, but no exception dialog, and stack trace in method main
}
}
}
}
class Application
{
public void ProcessRequest()
{
try
{
Console.WriteLine("Doing stuff");
throw new InvalidOperationException("Legit exception handled by application");
}
catch (InvalidOperationException ex)
{
Console.WriteLine("Application handled exception \"{0}\"", ex.Message);
}
throw new InvalidOperationException("Unhandled exception"); // #1. Something is wrong here
}
}
程序的输出:
Doing stuff
FirstChanceException event raised in ExceptionTest: "Legit exception handled by application"
Application handled exception "Legit exception handled by application"
FirstChanceException event raised in ExceptionTest: "Unhandled exception"
Server swallowed an exception "Unhandled exception"
【问题讨论】:
-
调试器总是会在
Debugger.Break();或者在抛出异常而没有人捕捉到它的地方中断。如果您有类似try { ... } catch { /* dang! */ ExceptionHandler(); }的内容,您应该仍然可以看到堆栈跟踪,这应该会引导您找到原始异常。我也会将异常传递给ExceptionHandler,以确保它可以随时用于分析。最后一点:这可能不是实现您想要的最佳方式,最终目标到底是什么? -
我想用效果更好的东西替换
Debugger.Break();。我的目标是打破由全局异常处理程序处理的异常。但不仅仅是中断,而是与异常上下文中断。 -
Debugger.Break();不与上下文中断吗?我相当肯定它会在您使用的任何调试程序中为您提供堆栈跟踪? -
某事引发了该异常,因此
throw语句的行有问题,包含Debugger.Break()的行没有问题。我不会调试异常处理程序,而是会调试生成这些异常的类。 -
@user2029276,实际上我们经常启用异常设置,因为你不想使用这种方式,你可以在这里查看所有异常处理最佳实践:stackify.com/csharp-exception-handling-best-practices,也许你可以得到方法你想在那里使用。
标签: c# exception-handling visual-studio-debugging