Skip to content

Add custom middleware for global exception handling #184

Open
@nanotaboada

Description

@nanotaboada

Description

Propose a custom middleware to handle exceptions globally in the application. The middleware should catch unhandled exceptions, log the error details, and return a standardized error response. The response format should follow RFC 7807 (Problem Details for HTTP APIs), ensuring consistency and better error representation in API responses.

Acceptance Criteria

  • Create a middleware component to handle global exceptions.
  • Return standardized error responses in RFC 7807 format including type, title, status, detail, and instance (optional).
  • Ensure the middleware is registered in the application pipeline.
  • Add unit tests to validate the middleware behavior.

Suggested Approach

  • Create ExceptionMiddleware.cs
public class ExceptionMiddleware
{
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        try { await next(context); }
        catch (Exception ex)
        {
            context.Response.ContentType = "application/problem+json";
            var problem = new ProblemDetails
            {
                Title = "An error occurred",
                Detail = ex.Message,
                Status = (int)HttpStatusCode.InternalServerError
            };
            await context.Response.WriteAsync(JsonSerializer.Serialize(problem));
        }
    }
}
  • Register in Program.cs:
app.UseMiddleware<ExceptionMiddleware>();

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    .NETPull requests that update .NET codeenhancementNew feature or requestgood first issueGood for newcomers

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions