Created
August 27, 2013 07:14
-
-
Save lkaczanowski/6350545 to your computer and use it in GitHub Desktop.
MVC Global error handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| protected void Application_Error(Object sender, EventArgs e) | |
| { | |
| var httpContext = ((MvcApplication)sender).Context; | |
| var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(httpContext)); | |
| var currentController = " "; | |
| var currentAction = " "; | |
| if (currentRouteData != null) | |
| { | |
| if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString())) | |
| { | |
| currentController = currentRouteData.Values["controller"].ToString(); | |
| } | |
| if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString())) | |
| { | |
| currentAction = currentRouteData.Values["action"].ToString(); | |
| } | |
| } | |
| Exception ex = Server.GetLastError(); | |
| var controller = new ErrorController(); | |
| var routeData = new RouteData(); | |
| var action = "InternalError"; | |
| if (ex is HttpException) | |
| { | |
| var httpEx = ex as HttpException; | |
| switch (httpEx.GetHttpCode()) | |
| { | |
| case (int)HttpStatusCode.NotFound: | |
| action = "NotFound"; | |
| break; | |
| default: | |
| _log.ErrorIfIsEnabled(string.Format("While executing action <{0}> on controller <{1}> an exception was thrown.", currentAction, currentController), ex); | |
| action = "InternalError"; | |
| break; | |
| } | |
| } | |
| else if (ex is FaultException<WcfValidationFault>) | |
| { | |
| var validationFault = ex as FaultException<WcfValidationFault>; | |
| _log.ErrorIfIsEnabled(() => "Validation fault : \r\n " + validationFault.Detail.DumpValidationErrors("\r\n ")); | |
| action = "ValidationFault"; | |
| } | |
| else | |
| { | |
| _log.ErrorIfIsEnabled("Exception occured : ", ex); | |
| } | |
| httpContext.ClearError(); | |
| httpContext.Response.Clear(); | |
| httpContext.Response.StatusCode = ex is HttpException ? ((HttpException)ex).GetHttpCode() : (int)HttpStatusCode.InternalServerError; | |
| httpContext.Response.TrySkipIisCustomErrors = true; | |
| routeData.Values["controller"] = "Error"; | |
| routeData.Values["action"] = action; | |
| controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction); | |
| ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(httpContext), routeData)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment