Handle .net exceptions at application level

2020-07-25 10:15发布

问题:

I was reading a couple of articles a while back which I think described a behaviour where you can, in a .net application (specifically VB.net), allow an exception to occur, and then handle it in some kind of application-level exception handler, as opposed to within a Try/Catch block. My google-fu is weak at the moment, so I'm not having much luck guessing what this feature is called in order to find information about it.

If this rings a bell for any of you, can you point me in the right direction on what exactly the feature is called so that I can search for it?

Sample code is always welcome, of course, but this is mostly just a case of me forgetting the name of the feature and being unable to search for it.

回答1:

I believe you are looking for the AppDomain.UnhandledException event. This will allow you to handle any exception that is unhandled in the AppDomain of your choice. Most applications only have a single AppDomain so this code should do the trick

AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf MyHandler

However, actually attempting to handle the event here is not the best idea. This will fire for any exception thrown from any part of the code. This could very easily be an exception that is fatal to some component you depend on and handling it could lead to further, worse errors down the road.

I usually use this event purely logging and error reporting scenarios.



回答2:

This link http://msdn.microsoft.com/en-us/library/3a02k5s0(VS.80).aspx will show you how to add the handler. I agree that it is not a good idea to handle exceptions this way. IMHO it is the handler of last resort.



回答3:

Jeff Atwood wrote a great CodeProject article entitled 'User Friendly Exception Handling' http://www.codeproject.com/KB/exception/ExceptionHandling.aspx which I found really useful as the basis for building a custom handler of last resort. It's in VB.Net but has a C# translation in the comments.



回答4:

For web applications you can handle it in the Global.asax.cs in the Application_Error method. Here's our code:

protected void Application_Error(object sender, EventArgs e)
    {
        Exception ex = HttpContext.Current.Server.GetLastError();

        if (ex is HttpUnhandledException && ex.InnerException != null)
            ex = ex.InnerException;

        SendErrorMail(ex);  //Or log in database or whatever you want to do with it
    }