Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which HTTP Status Codes to cover for MVC error handling

I'm currently developing custom error pages in my error handling code for my MVC application. But I'm unclear as to which HTTP status codes I'm meant to cover.

Question: is there a typical list of HTTP status codes that should be catered for?

Alot articles which explain how to do MVC error handling and custom error pages but appear to only show several of the HTTP Status Codes: 403, 404, and 500 in their error handling code. What about HTTP Status Code: 408 as an example? Should this be covered? What about the tonne of other status codes - HTTP status codes on wiki

This may sound like a dumb question, but I really don't know the answer and can't find an information on this. Am I missing something here, i.e. should only a subset of status codes be covered?

If it helps, below is what I've done for my MVC error handling. This code (so far with the little testing that I've done) covers 404, and all 50x type exceptions:

1 In web.config, and entry for each HTTP status code I want to cover

<httpErrors errorMode="Custom" existingResponse="Replace" >
  <remove statusCode="403" />
  <remove statusCode="404" />
  <remove statusCode="500" />
  <error statusCode="403" responseMode="ExecuteURL" path="/Error/Forbidden" />
  <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
  <error statusCode="500" responseMode="ExecuteURL" path="/Error" />
</httpErrors>  

2 An error controller

    namespace MyApp.Controllers
    {
      public class ErrorController : Controller
      {
      public ActionResult Index()
      {
        return View();
      }
      public ActionResult Forbidden()
      {
        return View();
      }
      public ActionResult NotFound()
      {
        return View();
      }

3 User friendly error pages:

/Views/Shared/Index.cshtml
/Views/Shared/Forbidden.cshtml
/Views/Shared/NotFound.cshtml

4 ELMAH for logging

Further findings at 2 Nov 2015

Something I've just discovered that has been staring me in the face which I've missed... In IIS, the default Error pages covered are:

  • 401 – Unauthorized
  • 403 – Forbidden
  • 404 – Not Found
  • 405 – Method Not Allowed
  • 406 – Not Acceptable
  • 412 – Precondition Failed
  • 500 – Internal Server Error
  • 501 – Not Implemented
  • 502 – Bad Gateway

If this is good range Microsoft have set, then I will go by this as a guide going forwards!

like image 588
OpcodePete Avatar asked Jan 09 '15 12:01

OpcodePete


People also ask

What is used to handle an error in MVC?

Summary on MVC Error Handling You can use HandleErrorAttribute or OnException to provide fine-grained control of how you display error type messages to your users.

Which of the following codes shows how exceptions are handled in MVC?

HandleError Attribute This filter handles all the exceptions raised by controller actions, filters, and views. To use this feature, first of all turn on the customErrors section in web. config.

What HTTP status code typically has to deal with server errors?

HTTP Status Code 500 - Internal Server Error Instead of the problem being with pages missing or not found, this status code indicates a problem with the server. A 500 is a classic server error and will affect access to your site.

What are the HTTP status codes for client errors?

4xx Status Codes (Client Error) The request could not be understood by the server due to incorrect syntax. The client SHOULD NOT repeat the request without modifications.


2 Answers

There may be another way: this solution uses 1 custom-error page to handle all types (I think?)

[1]: Remove all 'customErrors' & 'httpErrors' from Web.config

[2]: Check 'App_Start/FilterConfig.cs' looks like this:

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

[3]: in 'Global.asax' add this method:

public void Application_Error(Object sender, EventArgs e)
{
    Exception exception = Server.GetLastError();
    Server.ClearError();

    var routeData = new RouteData();
    routeData.Values.Add("controller", "ErrorPage");
    routeData.Values.Add("action", "Error");
    routeData.Values.Add("exception", exception);

    if (exception.GetType() == typeof(HttpException))
    {
        routeData.Values.Add("statusCode", ((HttpException)exception).GetHttpCode());
    }
    else
    {
        routeData.Values.Add("statusCode", 500);
    }

    Response.TrySkipIisCustomErrors = true;
    IController controller = new ErrorPageController();
    controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
    Response.End();
}

[4]: Add 'Controllers/ErrorPageController.cs'

public class ErrorPageController : Controller
{
    public ActionResult Error(int statusCode, Exception exception)
    {
         Response.StatusCode = statusCode;
         ViewBag.StatusCode = statusCode + " Error";
         return View();
    }
}

[5]: in 'Views/Shared/Error.cshtml'

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = (!String.IsNullOrEmpty(ViewBag.StatusCode)) ? ViewBag.StatusCode : "500 Error";
}

<h1 class="error">@(!String.IsNullOrEmpty(ViewBag.StatusCode) ? ViewBag.StatusCode : "500 Error"):</h1>

//@Model.ActionName
//@Model.ContollerName
//@Model.Exception.Message
//@Model.Exception.StackTrace
like image 135
ubik404 Avatar answered Oct 11 '22 16:10

ubik404


An interesting question, IMHO.

These three errors (403, 404 and 500) are the most common errors that can happen to the real user accessing your site with a standard browser.

On other hand, the HTTP standard was written for both server and agent developers in order to define how both sides should operate. Naturally, the standard browsers like IE, Chrome, Firefox, etc. as well as the standard robots like Google or Bing bots correctly fulfill the requirements, but some proprietary written agent may send a malformed request, and the standard provides the set of codes the server should send in this situation. For example, if the Content-Length field is missed the server returns the error code 411. However, you shouldn't provide user-friendly pages for such a situation.

The code 408 (Request timeout) is explained in the standard as following:

"The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time."

and it also not a case you should make user-friendly page for.

To make a long story short, don't worry :)

like image 22
Alexander Dayan Avatar answered Oct 11 '22 18:10

Alexander Dayan