3

I've got ErrorController which customly handles my website errors.

It's pretty standard:

public class ErrorController : BaseController
{
    public ActionResult Error404(Exception ex)
    {
        return View();
    }
    public ActionResult Error500(Exception ex)
    {
        return View();
    }
}

However, in case if some rendering exception occurs inside of the View code (and this might occur, as the page has Master page (master layout) and different might happen), then I am not able to catch that rendering exception.

I can really see that exception with implementing ActionFilterAttribute.OnResultExecuted:

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        if (filterContext.Exception != null)
        {
            // not sure what to do here
        } else base.OnResultExecuted(filterContext);
    }

but in that case MVC looks for ~/Shared/Error.cshtml (incl. this path) after that exception occurs, and I can't provide the Errors view rendering exception to the user -- the "Last chance exception".

Is there any way to handle that?

Agat
  • 4,577
  • 2
  • 34
  • 62

1 Answers1

1

Here is a nice article on Exception handling in ASP.Net MVC that should help

Method 4:- Inheriting from “HandleErrorAttribute”

public class CustomHandleErrorAttribute: HandleErrorAttribute
{
    public override void OnException(ExceptionContext filterContext)
    {
        Exception ex = filterContext.Exception;
        filterContext.ExceptionHandled = true;
        var model = new HandleErrorInfo(filterContext.Exception, "Controller", "Action");

        filterContext.Result = new ViewResult()
        {
            ViewName = "Error",
            ViewData = new ViewDataDictionary(model)
        };
    }
}

And you attach that to your base controller.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • Alright, thanks! That really works. But then, if there is any way to catch the exception of `Error.cshtml` view rendering? (As it's called (rendered) then without additional action calling - just like the last action called it instead of the view with prev exception). – Agat Mar 10 '16 at 15:38