astral-api/Astral.ApiServer/Middleware/StatusCodeMiddleware.cs
Mike 81aa0ec1c0
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
WIP heartbeat and user presence
2024-12-15 16:06:14 +00:00

99 lines
3.3 KiB
C#

// <copyright file="StatusCodeMiddleware.cs" company="alveus.dev">
// Copyright (c) alveus.dev. All rights reserved. Licensed under the MIT License.
// </copyright>
using Astral.ApiServer.Core;
using Astral.ApiServer.Models.Common;
using Astral.Core.Constants;
namespace Astral.ApiServer.Middleware;
/// <summary>
/// Handle status code responses.
/// </summary>
public class StatusCodeMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<StatusCodeMiddleware> _logger;
/// <summary>
/// Initializes a new instance of the <see cref="StatusCodeMiddleware" /> class.
/// </summary>
/// <param name="next">Instance of <see cref="RequestDelegate" />.</param>
/// <param name="logger">Instance of <see cref="ILogger{StatusCodeMiddleware}" />.</param>
public StatusCodeMiddleware(
RequestDelegate next,
ILogger<StatusCodeMiddleware> logger)
{
_next = next;
_logger = logger;
}
/// <summary>
/// Invoke middleware.
/// </summary>
/// <param name="context">Instance of <see cref="HttpContext" />.</param>
public Task Invoke(HttpContext context)
{
return InvokeAsync(context);
}
private async Task InvokeAsync(HttpContext context)
{
await _next(context);
switch (context.Response.StatusCode)
{
case 401:
context.Response.Headers.Clear();
context.Response.ContentType = "text/json";
await context.Response.WriteAsJsonAsync(new ErrorResponseModel
{
Error = CoreErrorCodes.Unauthorized,
Message = "You're not authorized to do that"
});
break;
case 404:
context.Response.Headers.Clear();
context.Response.ContentType = "text/json";
_logger.LogWarning("Request to non-existing endpoint: {endpoint}", context.Request.Path);
await context.Response.WriteAsJsonAsync(new ErrorResponseModel
{
Error = ApiErrorCodes.UnknownMethod,
Message = "Unknown method"
});
break;
case 405:
context.Response.Headers.Clear();
context.Response.ContentType = "text/json";
await context.Response.WriteAsJsonAsync(new ErrorResponseModel
{
Error = ApiErrorCodes.IllegalMethod,
Message = "Illegal method"
});
break;
case 415:
context.Response.Headers.Clear();
context.Response.ContentType = "text/json";
await context.Response.WriteAsJsonAsync(new ErrorResponseModel
{
Error = ApiErrorCodes.UnsupportedBody,
Message = "Unsupported body/media type"
});
break;
case 500:
context.Response.Headers.Clear();
context.Response.ContentType = "text/json";
await context.Response.WriteAsJsonAsync(new ErrorResponseModel
{
Error = ApiErrorCodes.UnknownError,
Message = "Unknown error"
});
break;
}
}
}