views:

279

answers:

2

One of the filters on an application I'm developing checks to see if a user owns the item they are trying to alter. The action is decorated by the [RequiresOwnership] attribute, and inside the attribute logic, I check to see if the user owns the item, and if they don't, I throw an UnauthorizedAccessException.

My question is this: Where can I catch that exception? I would ideally like to redirect the user to a page explaining why what they tried to do wasn't allowed, instead of just showing an exception page. I don't think I would be catching the exception inside the action that is decorated by the attribute, so is there some base part of the application where I can handle exceptions thrown higher up, in the .NET MVC model?

EDIT: I realize that I could just redirect to a page via the filter itself, but that seems a little hacky to me. It would be nice to throw exceptions via attributes, and have one standard place where they can be caught and dealt with.

A: 

I think what you want is the [HandleError] attribute on your controller, which takes an optional path to an error handler view. The default is ~/Views/Shared/Error.aspx; you could add additional support for your specific exception there.

GalacticCowboy
A: 

I had this problem, and the way I solved it was to add the exception to the FilterContext's TempData collection instead of throwing it. You can then check for it in your action method, re-throw it and deal with it appropriately:

In the attribute:

if (/*some error condition*/)
   filterContext.Controller.TempData["Err"] = new Exception("An error");

And in the action method:

var e = TempData["Err"] as Exception;
if (e != null)
    throw e;

It's a less than ideal solution, but as you mentioned, there's no useful place to catch exceptions from attributes.

Lee D