I have a bit of code which performs error handling for me displaying particular views depending on the error received.
My code looks like this:
protected void Application_EndRequest()
{
var response = new HttpResponseMessage((HttpStatusCode)Context.Response.StatusCode);
if (!response.IsSuccessStatusCode)
{
var rd = new RouteData();
IController c = new ErrorController();
switch (response.StatusCode)
{
case HttpStatusCode.BadRequest:
Response.Clear();
rd.Values["controller"] = "Error";
rd.Values["action"] = "BadRequest";
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
break;
case HttpStatusCode.NotFound:
Response.Clear();
rd.Values["controller"] = "Error";
rd.Values["action"] = "NotFound";
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
break;
case HttpStatusCode.InternalServerError:
Response.Clear();
rd.Values["controller"] = "Error";
rd.Values["action"] = "InternalServerError";
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
break;
case HttpStatusCode.Forbidden:
Response.Clear();
rd.Values["controller"] = "Error";
rd.Values["action"] = "Forbidden";
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
break;
default:
Response.Clear();
rd.Values["controller"] = "Error";
rd.Values["action"] = "GenericError";
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
break;
}
}
This works for standard http status codes and as defined in the documentation, and response code of 200-299 doesnt get handled and passes through.
However, my question is, is this the best way to do it?
This arose from one of my requests returning a status code of 302 - Found. Now, according to the documentation, this would not be classified as a successful code, however, i do not see how it cannot be classified as successful.
Therefore is there a better way to do this to account for all successful codes rather than just 200-299?
Many Thanks for any input and opinions. I understand there may not be an absolute answer to this.
Putting 1 suggestion out there would be to change the if statement to:
if(!(statuscode >= 400 && statuscode <= 599)
This is because 4xx codes are defined as client errors and 5xx codes are defined as server errors. Therefore it should catch them all??
But what to do about the dreaded 418? :)
EDIT
I have attempted using httpErrors:
<httpErrors errorMode="Custom" existingResponse="Replace">
<clear/>
<error path="/Error/NotFound" responseMode="ExecuteURL" statusCode="400"/>
</httpErrors>
As well as customErrors in web.config:
<customErrors mode="On" defaultRedirect="~/Error">
<error statusCode="404" redirect="~/Error/NotFound" />
<error statusCode="403" redirect="~/Error/Forbidden" />
<error statusCode="500" redirect="~/Error/InternalServerError" />
</customErrors>
Both with no luck