Skip to content

Instantly share code, notes, and snippets.

@ismkdc
Created April 12, 2023 16:02
Show Gist options
  • Save ismkdc/3f0717532757707011985614f342250b to your computer and use it in GitHub Desktop.
Save ismkdc/3f0717532757707011985614f342250b to your computer and use it in GitHub Desktop.
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