How to hander exception in MVC2
Based on doing more and more practise, it seems that there are two exception source in MVC2. Before Action and After Action. I means that the exception caused before the incoming request been ActionInvoked and after been processed.
As is we know, every MVC request go through probably the following steps:
Request--->ControllerFactory-->Controller-->Action Invoker-->Action Method--->Response
Actally, if the request does do invoke certain action. We can catch the exception in Application_Error event in Global.asax.
If the exception caused by invoking certain action. We can hander the exception as following points:
1. Overrider OnException method in Controller or derive from FilterAttribute and implement IExceptionFilter(if you hope to save the exception in TempData variable).
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext.ExceptionHandled) return;
filterContext.Controller.TempData["Exception"] = filterContext.Exception;
filterContext.Result = new RedirectToRouteResult("Default", new System.Web.Routing.RouteValueDictionary(
new { action = "OnError" }
));
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
}
2. Create cutomize ActionFiltterAttribute and implement ActionFilterAttribute.
public class MyactionFitter :ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Exception != null)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new RedirectToRouteResult("Default", new System.Web.Routing.RouteValueDictionary(
new { action = "OnError" }
));
}
}
You can mark the Controller or certain action with the predicated attribute.
namespace MvcApplication1.Controllers
{
[MyactionFitter]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
return View();
}
public ActionResult OnError() {
return View();
}
public ActionResult RaiseError()
{
string[] arr = new string[1];
string s = arr[2];
return RedirectToAction("index");
}
}
}
浙公网安备 33010602011771号