title: ASP.NET Application_Error being invoked twice
body: <p>I use <code>Application_Error</code> to handle errors in an ASP.NET MVC 3 application. Today I noticed that for one particular error case, this method is called twice: When requesting a resouce with a leading underscore, as e.g. <code>_ViewStart.cshtml</code>.</p>
  
  <p>The implementation of <code>Application_Error</code> consumes the last server error:</p>
  
  <pre><code>var exception = server.GetLastError();
  server.ClearError();
  ...
  </code></pre>
  
  <p>Therefore, when it's called for the second time, <code>GetLastError</code> returns <code>null</code>. When it's called for the first time, it sets a corresponding status code and content on the response object. The second invocation then caused all these settings to be overwritten. To work around this issue, I now check for a null pointer:</p>
  
  <pre><code>if (exception == null) return;
  </code></pre>
  
  <p>This way, it works perfectly fine: The first run of the method replaces the response by an error page and sets the status code. The second run does nothing. Then the response is sent to the client who gets the correct status code and error page.</p>
  
  <p>But this line of code looks like dirty to me. I would prefer to understand what is going on rather than having the error handler quit silently when in fact something must have gone wrong.</p>
  
  <p>Please note: It seems like no exception is thrown anywhere during the first run of the error handling. Otherwise I could understand it. But when debugging it line by line, the whole <code>Application_Error</code> method is processed, including an MVC call to a controller and the rendering of the views. In fact, after following gordonml's comment and checking the "Break when CLR exception is thrown" flag, Visual Studio did never break, not even before the first invocation of Application_Error.</p>