0

I have a custom exception that gets thrown in certain cases. When it gets thrown, I want to render a particular view and output it to the response.

Before I begin, yes, I have <customErrors mode="On" /> in my root-level Web.config.

I am doing almost exactly what Darin suggested in this answer:

public class EntityNotFoundHandleErrorAttribute : HandleErrorAttribute {

    public override void OnException(ExceptionContext filterContext) {
        if (!filterContext.IsChildAction && !filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled && filterContext.Exception is EntityNotFoundException) {
            string controllerName = (string)filterContext.RouteData.Values["controller"];
            string actionName = (string)filterContext.RouteData.Values["action"];
            HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName);
            ViewResult result = new ViewResult {
                ViewName = this.View,
                ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
                TempData = filterContext.Controller.TempData
            };
            filterContext.Result = result;
            filterContext.ExceptionHandled = true;
            filterContext.HttpContext.Response.Clear();
            filterContext.HttpContext.Response.StatusCode = 500;
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
        }
    }

}

and registering it in FilterConfig.cs (called from Global.asax):

public static void RegisterGlobalFilters(GlobalFilterCollection filters) {

    filters.Add(new EntityNotFoundHandleErrorAttribute() {
            ExceptionType = typeof(Inspect.Models.EntityNotFoundException),
            View = "NotFound",
            Order = 2
    });


    // Commented out just to be sure this isn't screwing it up.
    // filters.Add(new Utilities.ElmahHandleErrorAttribute(), 1);

}

The deal is, I can confirm that OnException is running as expected, but the view doesn't display. Instead, I get the unhelpful version of the yellow screen of death that tells me I should use the customErrors="RemoteOnly" if I want to see details.

The kicker is that all of this stuff works if I change the filterContext.Result to a RedirectResult. But I don't want to do that. I just want to write the view to the response.

Community
  • 1
  • 1
Andrew
  • 4,145
  • 2
  • 37
  • 42

1 Answers1

0

The value of this.View was "NotFound". Changing it to "~/Views/Errors/NotFound" solves the problem.

Andrew
  • 4,145
  • 2
  • 37
  • 42