Skip to content

Instantly share code, notes, and snippets.

@hgmauri
Last active February 28, 2024 12:41
Show Gist options
  • Save hgmauri/f3b43384937bf81a5b9950e69f857be1 to your computer and use it in GitHub Desktop.
Save hgmauri/f3b43384937bf81a5b9950e69f857be1 to your computer and use it in GitHub Desktop.
ErrorHandlingMiddleware.cs
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