https://brunomj.medium.com/net-5-0-web-api-global-error-handling-6c29f91f8951
public class GlobalErrorHandlingMiddleware
{
private readonly RequestDelegate _next;
public GlobalErrorHandlingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next.Invoke(context);
}
catch (Exception ex)
{
var response = context.Response;
response.ContentType = "application/json";
response.StatusCode = (int)HttpStatusCode.InternalServerError;
var errorResponse = new
{
message = ex.Message,
statusCode = response.StatusCode
};
var errorJson = JsonSerializer.Serialize(errorResponse);
await response.WriteAsync(errorJson);
}
}
}
// Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
// register middleware
app.UseMiddleware<GlobalErrorHandlingMiddleware>();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
486000cookie-check.NET 5 WebAPI: Middleware / Global Error Handling