【发布时间】:2016-01-14 01:38:11
【问题描述】:
我正在尝试处理 asp.net 5 控制台应用程序中未处理的异常,但我似乎无法使用相信的代码捕获这些错误。一旦抛出异常,代码就会中断。 dnx 应用中是否有任何方法可以捕获未处理的异常?
public class Program
{
[STAThread]
public static void Main(string[] args)
{
#if !DNXCORE50
// Register unhandled exception handler
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledExceptionHandler);
// Throw exception
throw new Exception("1");
#endif
Console.ReadLine();
}
#if !DNXCORE50
/// <summary>
/// Catch all unhandled exceptions in all threads.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs args)
{
try
{
// Get the exception that was thrown
Exception exceptionThrown = (Exception)args.ExceptionObject;
Console.WriteLine("Information coming from exception handler");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
#endif
}
【问题讨论】:
-
它没有被调用,因为您的异常是在控制台应用程序中引发的,而不是您的应用程序域的级别?换句话说,您在控制台应用程序中的异常被抛出的级别高于您侦听 UnhandledException 事件的级别。这有意义吗?
-
我想我明白你的意思,那么我需要做些什么来获取这些异常?
-
@DotnetShadow 请考虑下面的答案。
标签: asp.net asp.net-core dnx asp.net-core-1.0