title: ASP.NET MVC4 error handling for 404, 401 and other exceptions
body: <p>I'm struggling to understand how to correctly handle errors in ASP.NET MVC4. As an example, I've created a new MVC4 project using the "Internet Application" template and updated my home controller to test out some error cases:</p>
  
  <pre><code>public class HomeController : Controller
  {
      public ActionResult Index()
      {
          ViewBag.Message = "Hello";
          return View();
      }
  
      public ActionResult About()
      {
          throw new HttpException(401, "Not Authorized");
      }
  
      public ActionResult Contact()
      {
          throw new Exception("Oh no, some error occurred...");
      }
  }
  </code></pre>
  
  <p>I have enabled customErrors in my web.config file:</p>
  
  <pre><code>&lt;customErrors mode="On"&gt;&lt;/customErrors&gt;
  </code></pre>
  
  <p>When I run the app and click "Contact", I see the <em>~/Views/Shared/Error.cshtml</em> view as expected, since I have the <code>HandleErrorAttribute</code> registered as a global filter.</p>
  
  <p>However, when I click "About", I get the standard ASP.NET yellow error page that says "Runtime Error". <strong>Why are these two exceptions being handled differently and how can I get instances of <code>HttpException</code> to get caught using the <code>HandleError</code> attribute?</strong></p>
  
  <hr>
  
  <p><strong>CustomErrors config</strong></p>
  
  <p>Ideally, I'd like custom error pages for the following:</p>
  
  <ul>
  <li>A custom 404 (not found) page that's nice and user friendly</li>
  <li>A custom 401 (not authorised) page that informs the user that they do not have access (e.g. thrown after checking permissions for a particular item in the model)</li>
  <li>A generic error page that is used in all other cases (in place of the standard yellow ASP.NET page).</li>
  </ul>
  
  <p>I've created a new "Error" controller with views for each of the scenarios above. I have then updated customErrors in web.config like so: </p>
  
  <pre><code>&lt;customErrors mode="On" defaultRedirect="~/Error/Trouble"&gt;
      &lt;error statusCode="404" redirect="~/Error/NotFound"&gt;&lt;/error&gt;
      &lt;error statusCode="401" redirect="~/Error/NotAuthorized"&gt;&lt;/error&gt;
  &lt;/customErrors&gt;
  </code></pre>
  
  <p>The 404 page works fine, but <strong>I don't get the 401 page at all</strong>. Instead, I get the <em>~/Error/Trouble</em> view (the one specified as the <code>defaultRedirect</code>) when I try to access the <code>About</code> action on the <code>Home</code> controller. </p>
  
  <p><strong>Why is my custom 401 redirect page not working?</strong> </p>