Skip to content

Instantly share code, notes, and snippets.

@Seloris
Created February 21, 2022 22:47
Show Gist options
  • Save Seloris/ce9cf9fcafa5dfd6f67a969c3867ffe7 to your computer and use it in GitHub Desktop.
Save Seloris/ce9cf9fcafa5dfd6f67a969c3867ffe7 to your computer and use it in GitHub Desktop.
Gérer les exceptions de son API .NET Core - ExceptionMiddleware
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
await HandleExceptionAsync(httpContext, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var appError = new AppError(exception);
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)appError.StatusCode;
await context.Response.WriteAsync(appError.ToString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment