My goal is to create an error handling within the application that handles all managed errors, not just MVC related. So I\'m not using the HandleErrorAttribute pattern becau
If you want to handle this in your app you can write a custom handler or use the HandleError Attribute here is a good example of one way to approach this instead of having to use IIS as a crutch. as not all IIS host providers will allow this type of customization at the server level and IMO is a bad way to approach since it creates extra configuration at deployment time.
The reason you're seeing the behaviour is probably that your Application_Error
handler is correctly being invoked (and invoking your controller), but then IIS is intercepting the 500 error and displaying its own error page. (though it's also possible that your Application_Error
handler is itself throwing an Exception
, that's something you'll want to rule out)
Because you want to handle all errors (e.g. the static file error you mentioned), you will likely be unable to rely on either ASP.NET or ASP.NET MVC to do the initial error detection for you. Not all errors come from your application!
The best thing to do is to lean on IIS 7.5's error handling as much as you can, rather than try to get involved yourself too early. Let IIS do the initial error detection for you and it's much easier.
Try putting the following in your web.config
, replacing your existing httpErrors
node:-
<httpErrors errorMode="Custom" existingResponse="Replace">
<clear />
<error statusCode="400" responseMode="ExecuteURL" path="/Error" />
<error statusCode="403" responseMode="ExecuteURL" path="/Error/Forbidden" />
<error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
<error statusCode="500" responseMode="ExecuteURL" path="/Error" />
</httpErrors>
Remove the customErrors
node entirely. It is unnecessary.
Remember and make sure your error controller is setting the correct status code:-
public ActionResult Forbidden()
{
Response.StatusCode = 403;
return this.View();
}
You should then be able to ditch everything apart from the logging out of your Application_Error
handler - though I think you'd be best creating your own HttpModule
; setting runAllManagedModulesForAllRequests
on the modules node in your web.config
helps you catch errors that would otherwise slip through.
I've got this setup (though I'm personally using elmah to do the logging) running on the Azure Web Sites preview, and it's catching everything except from obviously any errors that come from failing to parse web.config
.
I've put a full working example of using httpErrors for custom error pages up on github. You can also see it live on azure web sites.