3

I am using app.UseExceptionHandler(GlobalErrorHandler) in AspNetCore and after that a custom middleware. When using this separately they work fine but when using them simultaneous the exception is thrown inside my custom middleware and crashes the call. This happens on await _next.Invoke(context). I also tried to use an ExceptionFilter but the results where the same. My global exception handling looks like this. Is there a way to stop the exception from bubbling up?

  app.UseCustomMiddleware();
  app.UseExceptionHandler(GlobalErrorHandler);
  app.UseMvc();


private void GlobalErrorHandler(IApplicationBuilder applicationBuilder)
{
  applicationBuilder.Run(
  async context =>
     {
       context.Response.ContentType = "text/html";
       var ex = context.Features.Get<IExceptionHandlerFeature>();
       if (ex != null)
       {
         string errorMessage;
         var webFault = ex.Error as WebFaultException<string>;
         if (webFault != null)
         {
           context.Response.StatusCode = (int)webFault.StatusCode;
           errorMessage = webFault.Detail;
         }
         else
         {
           if (ex.Error is UnauthorizedAccessException)
           {
             context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
             errorMessage = string.Empty;
           }
           else
           {
             context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
             errorMessage = ex.Error.Message + new StackTrace(ex.Error, true).GetFrame(0).ToString();
           }

           _logger.Error(errorMessage, ex.Error);
         }

         await context.Response.WriteAsync(errorMessage).ConfigureAwait(false);
       }
     });
}

1 Answer 1

6
+250

The problem is with the order in which you add middlewares to the application. Since you add exception handler after the custom middleware, any exception thrown by this middleware will not be covered by the exception filter.

The fix is very simple. Just change the order of middleware registration, so that exception filter is registered first:

app.UseExceptionHandler(GlobalErrorHandler);
app.UseCustomMiddleware();
app.UseMvc();

Now the exception thrown from the custom middleware will be successfully processed by the exception handler.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.