Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling route errors in ASP.NET MVC

I understand how to set up my own routes, but how does one handle routes that fall through the cracks of the routing table? I mean, I guess the default {controller}/{action}/{id} route could be a generic catchall, but I'm not sure if that's the way to go. I like letting my users know they've requested data/a 'page' that doesn't exist.

Is this where the [HandleError] filter comes in? How does that work, exactly?

like image 750
Major Productions Avatar asked Jan 28 '11 20:01

Major Productions


People also ask

How do we map the error to the view in MVC?

To pass error to the view we can use ModelState. AddModelError method (if the error is Model field specific) or simply ViewBag or ViewData can also be used.


2 Answers

If your route is not found, you want to handle it as a normal HTTP 404 error.

If you only add the [HandleError] attribute to your class or action, MVC will look for an Error view in your views folder.

You could also add an ErrorController or even a static page and add this to your Web.config:

<customErrors mode="On" >
    <error statusCode="404" redirect="/Error/PageNotFound/" />
</customErrors>

Or you could handle the HTTP 404 in your Global.asax.cs and route to an ErrorController programmatically. That's how I generally do it:

protected void Application_Error(object sender, EventArgs e)
{
    var ex = Server.GetLastError().GetBaseException();

    var routeData = new RouteData();

    if (ex.GetType() == typeof(HttpException))
    {
        var httpException = (HttpException)ex;

        switch (httpException.GetHttpCode())
        {
            case 404:
                routeData.Values.Add("action", "PageNotFound");
                break;
            default:
                routeData.Values.Add("action", "GeneralError");
                break;
        }
    }
    else
    {
        routeData.Values.Add("action", "GeneralError");
    }

    routeData.Values.Add("controller", "Error");
    routeData.Values.Add("error", ex);

    IController errorController = new ErrorController();
    errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
}
like image 73
Martin Buberl Avatar answered Oct 09 '22 06:10

Martin Buberl


You can define a route like this:

routes.MapRoute(
                "PageNotFound",
                "{*catchall}",
                new { controller = "Home", action = "PageNotFound" }
                );

Than make an action in a controller like this:

        public ActionResult PageNotFound()
        {
            ViewBag.Message = "Sorry, the page you requested does not exist.";
            return View();
        }

This route sould be added last, that way it will catch any request that can't be mapped.

HandleError attribute is used to catch exceptions that may occure within controller actions.

like image 45
frennky Avatar answered Oct 09 '22 05:10

frennky