Last active
February 28, 2024 12:41
-
-
Save hgmauri/f3b43384937bf81a5b9950e69f857be1 to your computer and use it in GitHub Desktop.
ErrorHandlingMiddleware.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ErrorHandlingMiddleware : Microsoft.AspNetCore.Diagnostics.IExceptionHandler | |
{ | |
public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken) | |
{ | |
using var property = LogContext.PushProperty("UserName", httpContext.User?.Identity?.Name ?? "anônimo"); | |
Log.Error(exception, "Error"); | |
var result = JsonSerializer.Serialize(new { error = exception?.Message }); | |
httpContext.Response.ContentType = "application/json"; | |
httpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; | |
await httpContext.Response.WriteAsync(result, cancellationToken: cancellationToken); | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment