开发者

replacement for try catch(MyEx ex) in each action

I need something that would work like this:

public ActionResult Ac()
{
  try {
   //stuff...
  }开发者_Go百科
  catch(MyException ex)
  {
   //handle
  }
}

but without putting try catch in each action method


You want to annotate your classes with HandleErrorAttribute - http://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute.aspx.

If the functionality of the built in handler above isn't sufficient then you can define your own class which implements IExceptionFilter - the OnException method takes an ExceptionContext object with Result and HttpContext properties you can use to control the outcome, something like:

public class MyHandleErrorAttribute : FilterAttribute, IExceptionFilter
{
  public void OnException(ExceptionContext filterContext)
  {
    Exception e = filterContext.Exception;

    // Do some logging etc. here

    if (!filterContext.ExceptionHandled && filterContext.HttpContext.IsCustomErrorEnabled)
    {
      ViewResult lResult = ...
      filterContext.Result = lResult;
      filterContext.ExceptionHandled = true;
      filterContext.HttpContext.Response.Clear();
      filterContext.HttpContext.Response.StatusCode = 500;
      filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
    }
  }


Use Exception Filters for exception handling.


How about

[HandleError(ExceptionType = typeof(MyException ), View = "MyErrView"))]
public ActionResult Ac()
{
    //stuff
}

but with a custom HandleError Attribute that handles the type of exceptions you are targeting. This SO question should give you a good start.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜