Created
February 21, 2022 22:47
-
-
Save Seloris/ce9cf9fcafa5dfd6f67a969c3867ffe7 to your computer and use it in GitHub Desktop.
Gérer les exceptions de son API .NET Core - ExceptionMiddleware
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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