/ErrorHandlerMiddleware,cs Secret
Created
May 17, 2022 22:13
Error Handler Middleware
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
using ApplicationCore.Exceptions; | |
using System.Net; | |
using System.Text.Json; | |
namespace WebApi | |
{ | |
public class ErrorHandlerMiddleware : IMiddleware | |
{ | |
private readonly RequestDelegate _next; | |
public ErrorHandlerMiddleware(RequestDelegate next) | |
{ | |
_next = next; | |
} | |
public async Task InvokeAsync(HttpContext context, RequestDelegate next) | |
{ | |
try | |
{ | |
await _next(context); | |
} | |
catch (Exception error) | |
{ | |
var response = context.Response; | |
response.ContentType = "application/json"; | |
switch (error) | |
{ | |
case CurrencyNotSupportedException: | |
case CurrencyExchangeNotFoundException: | |
case ArgumentOutOfRangeException: | |
response.StatusCode = (int)HttpStatusCode.BadRequest; | |
break; | |
case CurrencyNotFoundException: | |
response.StatusCode = (int)HttpStatusCode.NotFound; | |
break; | |
default: | |
// unhandled error | |
response.StatusCode = (int)HttpStatusCode.InternalServerError; | |
break; | |
} | |
var result = JsonSerializer.Serialize(new { message = error?.Message }); | |
await response.WriteAsync(result); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment