HOW TO ACHIVE ERROR HANDLING IN ASP.NET MVC

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
 877  View(s)
Ratings:
Rate this:

How can I correctly handle exceptions thrown from controllers in ASP.NET MVC? The HandleErrorattribute seems to only process exceptions thrown by the MVC infrastructure and not exceptions thrown by my own code.

Using this web.config

<customErrors mode="On">

    <error statusCode="401" redirect="/Errors/Http401" />

</customErrors>

with the following code

namespace MvcApplication1.Controllers

{

    [HandleError]

    public class HomeController : Controller

    {

        public ActionResult Index()

        {

            // Force a 401 exception for testing

            throw new HttpException(401, "Unauthorized");

        }

    }

}

doesn't result in what I was hoping for. Instead I get the generic ASP.NET error page telling me to modify my web.config to see the actual error information. However, if instead of throwing an exception I return an invalid View, I get the /Shared/Views/Error.aspx page:

return View("DoesNotExist");

Throwing exceptions within a controller like I've done above seems to bypass all of the HandleErrorfunctionality, so what's the right way to create error pages and how do I play nice with the MVC infrastructure?

  1. john rob

    Post:108

    Points:756
    Re: How to Achive Error Handling in ASP.NET MVC

    Thanks to kazimanzurrashaid, here is what I wound up doing in Global.asax.cs:

    protected void Application_Error()

    {

        Exception unhandledException = Server.GetLastError();

        HttpException httpException = unhandledException as HttpException;

        if (httpException == null)

        {

            Exception innerException = unhandledException.InnerException;

            httpException = innerException as HttpException;

        }

        if (httpException != null)

        {

            int httpCode = httpException.GetHttpCode();

            switch (httpCode)

            {

                case (int) HttpStatusCode.Unauthorized:

                    Response.Redirect("/Http/Error401");

                    break;

            }

        }

    }

    I'll be able to add more pages to the HttpContoller based on any additional HTTP error codes I need to support.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!