Question

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.

Was it helpful?

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,

OTHER TIPS

If you just want to force 'unhandled' exceptions like UnauthorizedAccessException to go through the normal custom-error page then you can override the controller's OnException method similar to the following:

    protected override void OnException(ExceptionContext filterContext)
    {
        base.OnException(filterContext);

        if (!filterContext.ExceptionHandled && filterContext.RequestContext.HttpContext.IsCustomErrorEnabled)
        {
            filterContext.ExceptionHandled = true;

            filterContext.HttpContext.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
            filterContext.Result = View("Error",
                new HandleErrorInfo(filterContext.Exception, filterContext.GetCurrentControllerName(), filterContext.GetCurrentActionName()));
        }
    }

The article that you referenced is an excellent resource for a more thorough explanation of error-handling techniques, though, and should be considered as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top