Jobert Enamno
Jobert Enamno

Reputation: 4461

MVC Route Error Handler

I want to catch the latest unhandled error application and redirect it to error page whenever error has occurred. But I got error "No matching route found for RedirectToRoute." What's the problem with my code? Here's my implementation:

Global.asax

routes.MapRoute(
        "ErrorHandler",
        "{ErrorHandler}/{action}/{errMsg}",
       new {controller="ErrorHandler", action = "Index", errMsg = UrlParameter.Optional }
       );

Application_End

 protected void Application_Error(object sender, EventArgs e)
        {
            var strError = Server.GetLastError().Message;
            if (string.IsNullOrWhiteSpace(strError)) return;
            Response.RedirectToRoute("ErrorHandler", new {controller="ErrorHandler", action = "Index", errMsg = strError });
            this.Context.ClearError();
        }

ErrorHandler Controller

public class ErrorHandlerController : Controller
    {

        public ActionResult Index(string errMsg)
        {
            ViewBag.Exception = errMsg;
            return View();
        }

    }

To Test the error handler on my Home Controller

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //just intentionally added this code so that exception will occur
            int.Parse("test");
            return View();
        }
    }

Updated

typo "contoller". Thanks to drch. But still I got error "No matching route found for RedirectToRoute."

Upvotes: 0

Views: 3398

Answers (1)

drch
drch

Reputation: 3070

There must be a problem with your route definitions.

The route you have:

routes.MapRoute(
    "ErrorHandler",
    "{ErrorHandler}/{action}/{errMsg}",
   new {controller="ErrorHandler", action = "Index", errMsg = UrlParameter.Optional }
   );

is VERY eager and will cause problems. That's going to match any url that's http://yoursite/anything/anything/*. Because your HomeController.Index is even being executed, it means that the routing was already matched with an even more greedy route (perhaps the default one?).

So there's 2 things -

1) you need to move your error handler route up higher. MVC uses the first matching route it finds in the route table.

2) make your route less greedy, ie:

routes.MapRoute(
    "ErrorHandler",
    "ErrorHandler/{action}/{errMsg}",
   new {controller="ErrorHandler", action = "Index", errMsg = UrlParameter.Optional }
   );

Upvotes: 4

Related Questions