控制台应用程序(DNX)中的ASP.NET Core 1.0 Global异常处理程序

时间:2016-01-14 01:38:11

标签: asp.net asp.net-core dnx asp.net-core-1.0

我试图在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

}

1 个答案:

答案 0 :(得分:0)

您可以在命令提示符下输出异常。

&#34; dnx命令引用影响其行为的几个环境变量,例如DNX_TRACE。

将DNX_TRACE环境变量设置为1,然后再次运行该应用程序。你应该看到更多的输出。&#34;

您可以阅读更多相关信息here