tags:

views:

35

answers:

3

I need something that would work like this:

public ActionResult Ac()
{
  try {
   //stuff...
  }
  catch(MyException ex)
  {
   //handle
  }
}

but without putting try catch in each action method

+2  A: 

Use Exception Filters for exception handling.

Adeel
+1  A: 

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.

Ahmad
+2  A: 

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;
    }
  }
Snafu