Skip to content

Instantly share code, notes, and snippets.

@leojh
Created July 6, 2012 00:42
Show Gist options
  • Save leojh/3057337 to your computer and use it in GitHub Desktop.
Save leojh/3057337 to your computer and use it in GitHub Desktop.
Global Error Handler For ASP.NET MVC 3
public static bool IsIt404NotFound(this Exception ex)
{
var httpException = ex as HttpException;
return httpException != null && httpException.GetHttpCode() == 404;
}
protected void Application_Error(object sender, EventArgs e)
{
var exception = Server.GetLastError();
if (exception.IsIt404NotFound())
{
renderNotFoundView();
}
else
{
renderErrorView(exception);
}
}
private void renderErrorView(Exception exception)
{
var exceptionMessageViewData = new[] { new KeyValuePair<string, object>("ExceptionMessage", exception)};
var currentHtppContextBase = HttpContext.Current.GetHttpContextBase();
currentHtppContextBase.RenderViewToHttpContextResponse("Error", viewDataPairs: exceptionMessageViewData);
currentHtppContextBase.SetStatusCodeTo(500);
}
private void renderNotFoundView()
{
var currentHtppContextBase = HttpContext.Current.GetHttpContextBase();
currentHtppContextBase.RenderViewToHttpContextResponse("NotFound", "NotFound");
currentHtppContextBase.SetStatusCodeTo(404);
}
internal static class HttpContextExtensions
{
internal static HttpContextBase GetHttpContextBase(this HttpContext httpContext)
{ return new HttpContextWrapper(httpContext);
}
internal static void SetStatusCodeTo(this HttpContextBase httpContextBase, int statusCode)
{
httpContextBase.Response.StatusCode = statusCode;
}
internal static void RenderViewToHttpContextResponse(this HttpContextBase httpContextBase, string viewName, string forceControllerName = null, IEnumerable<KeyValuePair<string, object>> viewDataPairs = null)
{
try
{
httpContextBase.Response.Clear();
var currentRequestContext = ((MvcHandler)httpContextBase.CurrentHandler).RequestContext;
var factory = ControllerBuilder.Current.GetControllerFactory();
var controllerName = string.IsNullOrEmpty(forceControllerName)
? currentRequestContext.RouteData.GetRequiredString("controller")
: forceControllerName;
var controller = factory.CreateController(currentRequestContext, controllerName);
var controllerContext = new ControllerContext(currentRequestContext, (ControllerBase)controller);
var viewResult = new ViewResult { ViewName = viewName };
if (viewDataPairs != null)
{
foreach (var viewData in viewDataPairs)
{
viewResult.ViewData.Add(viewData);
}
}
viewResult.ExecuteResult(controllerContext);
httpContextBase.Server.ClearError();
}
catch
{
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment