Tuesday, 24 February 2015

Passing Exception to Controller from Global asax

Came across this scenario where we have to redirect for all un-handled exceptions to user diplaying the StackTrace, Exception message and other details.

Global.asax
protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            Response.Clear();

            RouteData routeData = new RouteData();

            // Routing to ~/Error/Error
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "Error");
            routeData.Values.Add("error", exception);

            // clear error on server, not to display yellow error screen
            Server.ClearError();

            IController home = new TWC.IssueTrak.Mobile.Controllers.HomeController();
            home.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
            
        }


ErrorController
 public ActionResult Error(Exception exception)
        {
            return View("~/Views/Shared/_Error.cshtml",Exception);
        }


Error.cshtml
@model System.Exception
<div>Exception Message: <b>@Model.Message</b></div>

No comments:

Post a Comment