Asp.net-mvc – Global error handling (outside of controller) in ASP.NET MVC

asp.net-mvcerror handling

Let's say I put the following code somewhere in a Master page in my ASP.NET MVC site:

throw new ApplicationException("TEST");

Even with a [HandleError] attribute placed on my controller, this exception still bubbles up. How can I deal with errors like this? I would like to be able to route to an Error page and still be able to log the exception details.

What is the best way to deal with something like this?

Edit: One solution I was considering would be to add a a new controller: UnhandledErrorController. Can I put in an Application_Error method in Global.asax and then redirect to this controller (where it decides what to do with the exception)?

Note: the defaultRedirect in the customErrors web.config element does not pass along the exception info.

Best Answer

Enable customErrors:

<customErrors mode="On" defaultRedirect="~/Error">
    <error statusCode="401" redirect="~/Error/Unauthorized" />
    <error statusCode="404" redirect="~/Error/NotFound" />
</customErrors>

and redirect to a custom error controller:

[HandleError]
public class ErrorController : BaseController
{
    public ErrorController ()
    {
    }

    public ActionResult Index ()
    {
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        return View ("Error");
    }

    public ActionResult Unauthorized ()
    {
        Response.StatusCode = (int)HttpStatusCode.Unauthorized;
        return View ("Error401");
    }

    public ActionResult NotFound ()
    {
        string url = GetStaticRoute (Request.QueryString["aspxerrorpath"] ?? Request.Path);
        if (!string.IsNullOrEmpty (url))
        {
            Notify ("Due to a new web site design the page you were looking for no longer exists.", false);
            return new MovedPermanentlyResult (url);
        }

        Response.StatusCode = (int)HttpStatusCode.NotFound;
        return View ("Error404");
    }
}