0

I'm trying to get an unhandled exception handler to work but it doesn't seem to be doing anything. I have to following in the constructor:

AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);

And this furthur down

static void MyHandler(object sender, UnhandledExceptionEventArgs args)
    {
        Exception e = (Exception)args.ExceptionObject;
        if (log != null)
        {
            if (args.IsTerminating)
                log.LogError(e.Message, e.Source, e.InnerException.Message);
            else
                log.LogWarning(e.Message, e.Source, e.InnerException.Message);
        }
        else
        {
            System.Reflection.Assembly exe = System.Reflection.Assembly.GetEntryAssembly();
            string exeDir = System.IO.Path.GetDirectoryName(exe.Location);
            File.WriteAllText(DocuPath.Join(exeDir, "Emergency.log"), e.ToString());
        }
    }

log is a static object which handles logging to a file. Why don't I get a message in either the log file written to by the object or Emergency.log?

4

1 回答 1

2

如果e.InnerException为 null,则在此方法中会出现异常。
我认为在这里遇到这个问题不是一个好主意。

试试这个。

 string innerMessage = e.InnerException != null ? e.InnerException.Message : string.Empty;
 if (args.IsTerminating)
     log.LogError(e.Message, e.Source, innerMessage);
 else
     log.LogWarning(e.Message, e.Source, innerMessage);
于 2013-06-05T20:14:24.427 回答