Skip to content

Instantly share code, notes, and snippets.

@lkaczanowski
Last active November 14, 2020 00:33
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save lkaczanowski/5899045 to your computer and use it in GitHub Desktop.
Save lkaczanowski/5899045 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)
{
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;
_log.Error("Internal server error occurred while handling web request.", filterContext.Exception);
}
}
@stevensrf11
Copy link

rofl this sucks

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