Saturday, August 7, 2010

Using Application_Error instead of HandleError

I was behind the handle error attribute for handling error. but after all the research, I find using the Application_Error method in Global.asax found to be usefull , same as the old ASP.NET way. This was a solution post in ASP.NET forums


protected void Application_Error()
{
HttpContext ctx = HttpContext.Current;
KeyValuePair error = new KeyValuePair("ErrorMessage", ctx.Server.GetLastError().ToString());
ctx.Response.Clear();
RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
string controllerName = rc.RouteData.GetRequiredString("controller");
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(rc, controllerName);
ControllerContext cc = new ControllerContext(rc, (ControllerBase)controller);
ViewResult viewResult = new ViewResult { ViewName = "Error" };
viewResult.ViewData.Add(error);
viewResult.ExecuteResult(cc);
ctx.Server.ClearError();

}

No comments: