Open
Description
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
, andinstance
(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>();