Skip to content

Instantly share code, notes, and snippets.

@ludo6577
Created January 15, 2015 09:52
Show Gist options
  • Save ludo6577/b4e72f9aba6b720f7cef to your computer and use it in GitHub Desktop.
Save ludo6577/b4e72f9aba6b720f7cef to your computer and use it in GitHub Desktop.
protected void Application_Error(object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
HttpException httpException = exception as HttpException;
// Log the exception.
log.Info(String.Format("Application error: {0}:", exception));
log.Info(exception.StackTrace);
RouteData routeData = new RouteData();
routeData.Values["controller"] = "Errors";
routeData.Values["requestedUrl"] = Request.Url.OriginalString;
if (httpException == null)
{
return; //We ignore the rest of the method
//TODO: custom errors handling
//routeData.Values.Add("action", "Index");
}
else
{
switch (httpException.GetHttpCode())
{
case 404:
// Page not found.
routeData.Values.Add("action", "Http404");
break;
default:
return;
}
}
HttpContext httpContext = ((MvcApplication)sender).Context;
httpContext.Response.Clear();
httpContext.Response.ContentType = "text/html";
httpContext.Response.TrySkipIisCustomErrors = true;
httpContext.Response.StatusCode = httpException != null ? httpException.GetHttpCode() : 500;
Server.ClearError();
// Call target Controller and pass the routeData.
IController errorController = new ErrorsController();
try
{
errorController.Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData));
}
catch (Exception ex)
{
log.Info("Error in Global.asax: Application_Error():");
log.Info(ex.StackTrace);
string err = "<b>Error Caught in Global.asax: Application_Error() event</b><hr><br>" +
"<br><b>Error in: </b>" + Request.Url.ToString() +
"<br><b>Error Message: </b>" + ex.Message.ToString() +
"<br><b>Stack Trace:</b><br>" + ex.StackTrace.ToString();
Response.Write(err.ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment