mirror of
https://github.com/azaion/flights.git
synced 2026-04-22 08:26:31 +00:00
Initial commit
Made-with: Cursor
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
using System.Net;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace Azaion.Flights.Middleware;
|
||||
|
||||
public class ErrorHandlingMiddleware(RequestDelegate next, ILogger<ErrorHandlingMiddleware> logger)
|
||||
{
|
||||
public async Task Invoke(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
}
|
||||
catch (KeyNotFoundException ex)
|
||||
{
|
||||
await WriteError(context, HttpStatusCode.NotFound, ex.Message);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
await WriteError(context, HttpStatusCode.BadRequest, ex.Message);
|
||||
}
|
||||
catch (InvalidOperationException ex)
|
||||
{
|
||||
await WriteError(context, HttpStatusCode.Conflict, ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Unhandled exception");
|
||||
await WriteError(context, HttpStatusCode.InternalServerError, "Internal server error");
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task WriteError(HttpContext context, HttpStatusCode code, string message)
|
||||
{
|
||||
context.Response.StatusCode = (int)code;
|
||||
context.Response.ContentType = "application/json";
|
||||
var body = JsonSerializer.Serialize(new { statusCode = (int)code, message });
|
||||
await context.Response.WriteAsync(body);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user