Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handling Application_Error in ASP.NET app's global.asax

Tags:

asp.net

I wish to send mail to an administrator when the application crashes. So I simply do this in global.asax:

void Application_error(object sender, EventArgs e)
{
    SendMessageToAdministarator(Server.GetLastError().ToString());
}

But actually many times Application_Error is called even though the application won't crash.

And I wish to send mail to admin ONLY when the application crashed.

Also, do I have a simple way to lift the application back on?

I'm looking for the simplest solution.

like image 575
Hanan Avatar asked Jan 12 '09 09:01

Hanan


People also ask

How do you handle exceptions in global ASAX?

You can handle default errors at the application level either by modifying your application's configuration or by adding an Application_Error handler in the Global. asax file of your application. You can handle default errors and HTTP errors by adding a customErrors section to the Web. config file.

How does MVC handle application error in global ASAX?

Perhaps a better way of handling errors in MVC is to apply the HandleError attribute to your controller or action and update the Shared/Error. aspx file to do what you want. The Model object on that page includes an Exception property as well as ControllerName and ActionName.

What are the 3 approaches to handle exceptions in a web application?

try catch finally 2. Use error events to deal with exceptions within the scope of an object. Page_Error Global_Error Application_Error 3. Use custom error pages to display informational messages for unhandled exceptions within the scope of a Web application.


1 Answers

What kind of errors are send when the application is not crashed? You could check the type of exception and don't send emails on the exceptions that don't crash the app (for example a redirect can throw the ThreadAbortException which I manually filter in code):

protected void Application_Error(Object sender, EventArgs e) {     Exception ex = Server.GetLastError();     if (ex is ThreadAbortException)         return;     Logger.Error(LoggerType.Global, ex, "Exception");     Response.Redirect("unexpectederror.htm"); } 

You could add a redirect to an error page with a message for the user that an error has occured and some links to relevant pages in the site. This is for the 'lift the application back on' - I hope this is what you wanted.

Also you might look into logging with log4net which can also log errors on the server and send emails on errors.

like image 95
rslite Avatar answered Oct 05 '22 19:10

rslite