DD.WellWorkover.Cloud/AsbCloudWebApi/Middlewares/SimplifyExceptionsMiddleware.cs

64 lines
2.1 KiB
C#
Raw Normal View History

2023-06-30 17:57:00 +05:00
// Ignore Spelling: Middlewares
using AsbCloudApp.Exceptions;
using Microsoft.AspNetCore.Http;
using System;
using System.Threading.Tasks;
namespace AsbCloudWebApi.Middlewares
{
public class SimplifyExceptionsMiddleware
{
private readonly RequestDelegate next;
public SimplifyExceptionsMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await next.Invoke(context);
}
2022-04-11 18:00:34 +05:00
catch (ArgumentInvalidException ex)
{
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);
}
2022-04-11 18:00:34 +05:00
catch (ForbidException ex)
{
Console.WriteLine($"ForbidException in {context.Request.Method}: {ex.Message}");
context.Response.Clear();
context.Response.StatusCode = 403;
}
catch (OperationCanceledException ex)
{
Console.WriteLine(ex.Message);
}
2022-12-02 14:49:00 +05:00
catch (Exception ex) // TODO: find explicit exception. Use Trace. Add body size to message.
{
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)
{
object error = ex.ToValidationErrorObject();
var buffer = System.Text.Json.JsonSerializer.Serialize(error);
return buffer;
}
}
}