2024-07-04 11:02:45 +05:00
|
|
|
// Ignore Spelling: Middlewares
|
2023-06-30 17:57:00 +05:00
|
|
|
using AsbCloudApp.Exceptions;
|
2022-01-18 11:04:15 +05:00
|
|
|
using Microsoft.AspNetCore.Http;
|
2023-09-28 16:25:29 +05:00
|
|
|
using Microsoft.AspNetCore.Mvc;
|
2021-11-10 17:04:07 +05:00
|
|
|
using System;
|
2023-09-28 16:25:29 +05:00
|
|
|
using System.Collections.Generic;
|
2021-11-10 17:04:07 +05:00
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
2024-08-19 10:01:07 +05:00
|
|
|
namespace AsbCloudWebApi.Middlewares;
|
|
|
|
|
|
|
|
public class SimplifyExceptionsMiddleware
|
2021-11-10 17:04:07 +05:00
|
|
|
{
|
2024-08-19 10:01:07 +05:00
|
|
|
private readonly RequestDelegate next;
|
|
|
|
|
|
|
|
public SimplifyExceptionsMiddleware(RequestDelegate next)
|
2021-11-10 17:04:07 +05:00
|
|
|
{
|
2024-08-19 10:01:07 +05:00
|
|
|
this.next = next;
|
|
|
|
}
|
2021-11-10 17:04:07 +05:00
|
|
|
|
2024-08-19 10:01:07 +05:00
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
|
|
{
|
|
|
|
try
|
2021-11-10 17:04:07 +05:00
|
|
|
{
|
2024-08-19 10:01:07 +05:00
|
|
|
await next.Invoke(context);
|
2021-11-10 17:04:07 +05:00
|
|
|
}
|
2024-08-19 10:01:07 +05:00
|
|
|
catch (ArgumentInvalidException ex)
|
2021-11-10 17:04:07 +05:00
|
|
|
{
|
2024-08-19 10:01:07 +05:00
|
|
|
Console.WriteLine($"ArgumentException in {context.Request.Method}: {ex.Message}");
|
|
|
|
context.Response.Clear();
|
|
|
|
context.Response.StatusCode = 400;
|
|
|
|
context.Response.ContentType = "application/json";
|
|
|
|
var body = MakeJsonBody(ex);
|
|
|
|
await context.Response.WriteAsync(body);
|
2021-11-10 17:04:07 +05:00
|
|
|
}
|
2024-08-19 10:01:07 +05:00
|
|
|
catch (ForbidException ex)
|
2021-12-23 17:15:05 +05:00
|
|
|
{
|
2024-08-19 10:01:07 +05:00
|
|
|
Console.WriteLine($"ForbidException in {context.Request.Method}: {ex.Message}");
|
|
|
|
context.Response.Clear();
|
|
|
|
context.Response.StatusCode = 403;
|
2021-12-23 17:15:05 +05:00
|
|
|
}
|
2024-08-19 10:01:07 +05:00
|
|
|
catch (OperationCanceledException ex)
|
|
|
|
{
|
|
|
|
Console.WriteLine(ex.Message);
|
|
|
|
}
|
|
|
|
catch (Exception ex) // TODO: find explicit exception. Use Trace. Add body size to message.
|
|
|
|
{
|
|
|
|
if (context.Response.HasStarted)
|
|
|
|
throw;
|
|
|
|
|
|
|
|
context.Response.Clear();
|
|
|
|
context.Response.StatusCode = 500;
|
|
|
|
|
|
|
|
if (ex.Message.Contains("Reading the request body timed out due to data arriving too slowly. See MinRequestBodyDataRate."))
|
|
|
|
Console.WriteLine("Reading the request body timed out due to data arriving too slowly.");
|
|
|
|
else
|
|
|
|
throw;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private static string MakeJsonBody(ArgumentInvalidException ex)
|
|
|
|
{
|
|
|
|
var problem = new ValidationProblemDetails(ex.ErrorState);
|
|
|
|
var buffer = System.Text.Json.JsonSerializer.Serialize(problem);
|
|
|
|
return buffer;
|
2021-11-10 17:04:07 +05:00
|
|
|
}
|
|
|
|
}
|