title: .net core different error handling for API and Web Page controllers
body: <p>I'm trying to setup exception handling in a new .net Core 2.2 Web application project.</p>
  
  <p>Currently I tried two approaches - being</p>
  
  <ol>
  <li>Use the built-in ExceptionHandlers: <code>app.UseExceptionHandler</code>, <code>app.UseStatusCodePages</code>, etc...</li>
  <li>Created my own middleware to handle exceptions which I've added to the bottom of this question.</li>
  </ol>
  
  <p>Now, the main issue is that I can use my own custom middleware, but (of course) this is used on <em>all</em> requests, and not only on API calls.</p>
  
  <p>What I would like to achieve is have separated exception logic for Web API and Web Pages, so that I can use my custom middleware and return format for API, and use <code>app.UseDeveloperExceptionPage()</code> for example for web pages.</p>
  
  <h2>Exception middleware for reference:</h2>
  
  <pre><code>public static class ExceptionMiddleware
  {
      public static void ConfigureExceptionHandler(this IApplicationBuilder app, ILoggerFactory loggerFactory,
          bool includeStackTrace = false)
      {
          app.UseExceptionHandler(builder =&gt;
              builder.Run(async context =&gt;
              {
                  var logger = loggerFactory.CreateLogger(nameof(ExceptionMiddleware));
  
                  // Set the response status code
                  context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
                  context.Response.ContentType = "application/json";
  
                  var contextFeature = context.Features.Get&lt;IExceptionHandlerFeature&gt;();
                  if (contextFeature != null)
                  {
                      // Get the current exception
                      var currentException = contextFeature.Error;
                      logger.LogError(currentException, $"Something went wrong: {currentException}");
  
                      ErrorDetails errorDetails;
  
                      if (includeStackTrace)
                          errorDetails = new ExtendedErrorDetails
                          {
                              StatusCode = (HttpStatusCode) context.Response.StatusCode,
                              Message = currentException.Message,
                              StackTrace = currentException.StackTrace
                          };
                      else
                          errorDetails = new ErrorDetails
                          {
                              StatusCode = (HttpStatusCode) context.Response.StatusCode,
                              Message = "Internal Server Error."
                          };
  
                      // Write the response
                      await context.Response.WriteAsync(JsonConvert.SerializeObject(errorDetails));
                  }
              }));
      }
  
      private class ErrorDetails
      {
          public HttpStatusCode StatusCode { [UsedImplicitly] get; set; }
  
          public string Message { [UsedImplicitly] get; set; }
      }
  
      private class ExtendedErrorDetails : ErrorDetails
      {
          public string StackTrace { [UsedImplicitly] get; set; }
      }
  }
  </code></pre>