0

I have an endpoint that throws exception.

[ApiController]
[Route("api")]
public class LegacyController : ControllerBase
{
    [HttpPost("endpoint")]
    public async Task<ActionResult<IEnumerable<Entitty>>> GetAll()
    {
        throw new Exception();
        return Ok(t.ToList());
    }
}

I have custom Http logging filter that looks like this

using Microsoft.AspNetCore.Http;

namespace Client.API.Extensions
{
    public class HttpLoggingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

        public HttpLoggingMiddleware(RequestDelegate next, ILogger<HttpLoggingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            finally
            {
                _logger.LogInformation(
                    "Request {method} {url} => {statusCode}",
                    context.Request?.Method,
                    context.Request?.Path.Value,
                    context.Response?.StatusCode);
            }
        }
    }
}

When I'm calling this endpoint, context.Response?.StatusCode is 200. Why?

However, Postman shows me that my request failed, I see en error itself, therefore everything looks normal. Although logs contain 200 status code message, not the 500.

Edit: here is my startup (some parts are removed).

namespace Client.API
{
    public class Startup
    {
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            ...
            app.UseHttpsRedirection();

            app.UsePathBase(new PathString(basePath));
            app.UseRouting();

            app.UseMiddleware<HttpLoggingMiddleware>();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
            endpoints.MapControllers();
            });
        }
    }
}
5
  • You need to show your middleware configuration (Startup.Configure method). Most likely, your middleware is incorrectly registered Commented Feb 23, 2022 at 14:46
  • What is the purpose of all this weird code? What is your goal? To find a bug in MVC? Commented Feb 23, 2022 at 17:42
  • @Serge I'm implementing http logging for out service. This code is just an example to show that my code isn't working is it's intended and I don't know why Commented Feb 23, 2022 at 22:39
  • @osynavets It is http client stuff, but you even didn' t post http client request Commented Feb 23, 2022 at 22:42
  • @osynavets I tested the code , it returns 500 error. This is why I would like to see your httpclient code Commented Feb 24, 2022 at 0:06

1 Answer 1

1

If you want to catch the Exception, You need to use specific middleware--app.UseExceptionHandler();, So firstly I use this middleware to set the log.

The code is:

app.UseExceptionHandler(
  appErr =>
  {
    appErr.Run(
    async context =>
    {
      logger.LogInformation(
      "Request {method} {url} => {statusCode}",
       context.Request?.Method,
       context.Request?.Path.Value,
       context.Response?.StatusCode);
    });
});

But There is a problem, This middleware can only catch the exception, So when the response code is not 500, The request will not get into this middleware.

Finally I changed a method, I use try/catch to catch the exception and set the StatusCode by myself and it success. The code show as below:

public class HttpLoggingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<HttpLoggingMiddleware> _logger;

        public HttpLoggingMiddleware(RequestDelegate next,ILogger<HttpLoggingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception)
            {
                //catch the Exception and set the StatusCode 
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            }
            finally
            {
                _logger.LogInformation(
                    "Request {method} {url} => {statusCode}",
                    context.Request?.Method,
                    context.Request?.Path.Value,
                    context.Response?.StatusCode);
            }
        }

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

1 Comment

This line of code makes a difference. catch (Exception) { //catch the Exception and set the StatusCode context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; } For some reason even when exception occurs status code is still 200

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.