Search code examples
asp.net-mvcasp.net-mvc-4authorizationcustom-error-pagescustom-error-handling

Handling UnauthorizedAccessException with custom errors in MVC 4 Application


I have enabled the global error handling for an application by applying the HandleError attribute within the filterConfig registration.

 public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
    }
}

I am then using the custom errors (web.config) to hopefully display a friendly error message for each server error.

 <customErrors mode="On"  ></customErrors>

This seemed to be working fine for most exceptions and I was getting the expected behaviour in that the custom error page View (Error.cshtml in the shared view folder) was being displayed.

However I have recently noticed that this is not the behaviour I see if the error thrown is an UnauthorizedAccessException.

I am a bit stumped with this, as looking in fiddler I see that this UnauthorizedAccessException exception returns a plain 500 internal server error as a standard exception does.

So how come the standard exception abides by my customError setup but the UnauthorizedAccessException does not?

ANd how can I get them to behave the same, as they are both essentially an error which I want to prevent the end user from seeing.


Solution

  • This blog post provided me with the overview of exception handling to enable me to decide how to handle the unauthorizedAccessException, which essentially means handling them within the Application_OnStart.

    http://prideparrot.com/blog/archive/2012/5/exception_handling_in_asp_net_mvc

    For my purposes there doesn't seem much point in handling the errors with the HandleErrorAttribute and in the global Application_OnStart so for my purposes I decided it was best to handle everything in the Application_OnSTart,