josephwoodward / GlobalExceptionHandlerDotNet

Exception handling as a convention in the ASP.NET Core request pipeline
MIT License
269 stars 32 forks source link

Access to mapped status code in OnError handler #28

Closed codecontemplator closed 5 years ago

codecontemplator commented 5 years ago

In order to categorize my logging entry I would like to have access to the mapped status code. For example:

    app.UseGlobalExceptionHandler(x =>
    {
        x.ContentType = "application/json";
        x.ResponseBody(s => JsonConvert.SerializeObject(new
        {
            Message = "An error occurred whilst processing your request"
        }));

        x.Map<ArgumentNullException>().ToStatusCode(StatusCodes.Status400BadRequest);
        x.OnError((exception, httpContext) =>
        {
            if (<mappedStatusCode> >= 500) 
            {
               log.error(...);
            }
            else
            {
               log.warning(...);
            }
       }
);
josephwoodward commented 5 years ago

Hi @codecontemplator, thanks for raising this.

You can access the mapped status code via the httpContext argument (httpcontext.Response.StatusCode).

Is this what you were looking for or have I misunderstood your question?

Thanks, Joe

dharanish commented 5 years ago

Hi, @JosephWoodward thanks for your reply.

when I try to access httpContext.Response.StatusCode it always gives me 500 internal server error.

Could you please tell me if I am missing something.

codecontemplator commented 5 years ago

I experience the same thing. It seems like the OnError (logger) is invoked before the status code is resolved.

https://github.com/JosephWoodward/GlobalExceptionHandlerDotNet/blob/master/src/GlobalExceptionHandler/WebApi/ExceptionHandlerConfiguration.cs

dharanish commented 5 years ago

yeah @codecontemplator, I think _logger can be invoked after resolving status code.

josephwoodward commented 5 years ago

@dharanish @codecontemplator So it does! My test tests against a 500 which is why it was passing, I'll get that fixed.

codecontemplator commented 5 years ago

Thanks!

dharanish commented 5 years ago

Is it possible to provide any update on this issue.?

josephwoodward commented 5 years ago

@dharanish Yeah, working on a solution - hoping to get it out in the next few days. Ultimately I've created an overload that gives you some different options then I'll retire the older one ((Exception, HttpContext)) in the next major version release.

josephwoodward commented 5 years ago

Sorry it's taken me so long to get around to fixing this, however it's now been fixed in 4.0.1 which can be found on NuGet here. Decided to hold off on the above solution and instead just moved setting the status code before the log delegate is invoked. I'll close this issue now but please do let me know if there are any problems! 😄