Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I throw out an exception that happen in Application_Error handler in Global.asax?

The unhandled error codes in aspx.cs will be caught by Application_Error handler in global.asax.
I have write some codes in Application_Error handler to log such unhandled errors happened in aspx.cs
But if the codes of log itself also fails and generated a exception.(maybe due to I/O or files system problems)
Should I throw such exception out ?
If I throw it out, which event should receive such exception ?
Or it makes no difference if I write "throw" syntax or not ?
The code samples as following

protected void Application_Error(object sender, EventArgs e)
{
    try
    {
        // my codes to log exception to Database System here....
    }
    catch(Exception)
    {
        throw;  //Should I write "throw" syntax here ? 
    }
}
like image 445
Richard Avatar asked Feb 22 '13 06:02

Richard


1 Answers

Application_Error is the last place where you can log the exception that occurred before the thread (which is serving your request at the moment) gets aborted.

You don't need to throw any exception out of it because it will do so automatically after the function exits.

Here is a reasonable implementation of it.

I think your biggest concern is what to do if your fail over mechanism fails. In this case it's your logging. This is a bigger question in computers but building chained fail over mechanisms is generally a waste of time because in the end everything could fail (side suggestion for your own research: try to keep everything as stateless as possible). You best bet is to have a very reliable logging mechanism as your last resort which will be successful 99.9% of the time. Not going to go into how to create such mechanism (and it's not a good idea to do it yourself - create your own logger anyway as there is a lot of tricks to know to make sure that your logging is performant enough and non-obtrusive) but overall I'd recommend you to use elmah, it's likely the best logging framework currently available & it will serve your purpose.

For the very small amount of errors which may get by (which they likely won't in real life situation) I wouldn't lose sleep over them.

like image 89
user1416420 Avatar answered Oct 28 '22 02:10

user1416420