Handling UnauthorizedAccessException with User Errors in MVC 4 Application

I turned on global error handling for the application by applying the HandleError attribute in the filterConfig registration.

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

Then I use custom errors (web.config) to hopefully display a friendly error message for every server error.

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

It seemed to work fine for most exceptions, and I was getting the expected behavior in displaying a custom page with a View error (Error.cshtml in the general view folder).

However, I recently noticed that this is not the behavior that I see if the error was selected as UnauthorizedAccessException.

I am a bit stumped with this, as I look at the scratch, I see that this UnauthorizedAccessException returns a normal internal server 500 error, as does the standard exception.

So why is the standard exception thrown by my customError setting, but the UnauthorizedAccessException does not work?

ANd, how can I make them behave the same way, since they are essentially a mistake that I want to prevent the end user from seeing.

+4
source share
2 answers

This blog post provided me with an overview of exception handling so that I can decide how to handle unauthorizedAccessException, which essentially means handling them in Application_OnStart.

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

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

+1
source

If you just want to force "unhandled" exceptions, such as UnauthorizedAccessException , to pass through a regular page with a custom error, you can override the controller's OnException method, as shown below:

  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 you referred to is an excellent resource for a more detailed explanation of error handling methods, although it should be considered as well.

0
source

All Articles