2

I have a UsersController, with OnException (which works), but if I make the Controller inherit from BaseController, the OnException doesn't work, even if I put it in the BaseController.

Basically I want to have all my controllers inherit from BaseController so I can just have one OnException handler there, which catches everything...

1 Answer 1

5

You don't need to inherit from a custom base controller class in order to have all controllers handle exceptions the same way. You can do it with an ActionFilter.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, 
    AllowMultiple = true, Inherited = true)]
public class CustomHandleErrorAttribute : HandleErrorAttribute
{
    public override void OnException(ExceptionContext context)
    {
        // do custom exception handling here
        // to return View("Error"), you can just do this:
        context.Result = new ViewResult { ViewName = "Error" };
    }
}

You can apply this to all of the controllers in your library with this Global.asax:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    //filters.Add(new HandleErrorAttribute()); // default MVC setting
    filters.Add(new CustomHandleErrorAttribute());
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thankyou for your answer, its working :). brilliant. One question, how can I show my erorr view page from OnException? I cannot call View("Error") anymore because I'm not in a controller
@baconbeastnz might I suggest you ask that as another question. I for one am curious as to the answer
@Baconbeastnz and @Bryan Ross, I have updated my answer. Just about anything you can do from a controller, you can do from an action filter, you just have to do it a little differently. return View("Error") is just a method on System.Web.Mvc.Controller that constructs a ViewResult object. I suggest you download the MVC source code and have a look at it. You can always use it as a reference to figure out how to do stuff like this.
@danludwig, in this way you can't change the model (no setter). How can you transfer a model to your view?
@Shahar, you can add a model to the ViewResult when you construct it. new ViewResult { ViewName = "Error", ViewData = new ViewDataDictionary(new MyCustomViewModel()) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.