Created
April 12, 2023 16:02
-
-
Save ismkdc/3f0717532757707011985614f342250b to your computer and use it in GitHub Desktop.
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 Invoke(HttpContext context, ILogger<ExceptionMiddleware> logger) | |
{ | |
try | |
{ | |
await _next(context); | |
} | |
catch (Exception error) | |
{ | |
CustomError customError; | |
var response = context.Response; | |
switch (error) | |
{ | |
case CustomException e: | |
customError = e.CustomError; | |
response.StatusCode = (int)HttpStatusCode.BadRequest; | |
break; | |
default: | |
customError = CustomErrors.E_100; | |
logger.LogError(error.ToString()); | |
response.StatusCode = (int)HttpStatusCode.InternalServerError; | |
break; | |
} | |
await response.WriteAsJsonAsync( | |
customError | |
); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment