Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save johnkors/08edb7841d02eeb64ddb to your computer and use it in GitHub Desktop.

Select an option

Save johnkors/08edb7841d02eeb64ddb to your computer and use it in GitHub Desktop.
Custom ASP.NET MVC handle error attribute. Handles and logs all errors.
public class CustomHandleErrorAttribute : HandleErrorAttribute
{
private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public override void OnException(ExceptionContext filterContext)
{
_log.Error("Internal server error occurred while handling web request.", filterContext.Exception);
if (!filterContext.HttpContext.IsCustomErrorEnabled)
{
return;
}
if (!ExceptionType.IsInstanceOfType(filterContext.Exception))
{
return;
}
var controllerName = (string)filterContext.RouteData.Values["controller"];
var actionName = (string)filterContext.RouteData.Values["action"];
var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
filterContext.Result = new ViewResult
{
ViewName = View,
MasterName = Master,
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
@johnkors
Copy link
Copy Markdown
Author

Logging done regardless of customerrors on or off

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment