DD.WellWorkover.Cloud/AsbCloudWebApi/Middlewares/SimplifyExceptionsMiddleware.cs
Дмитрий Степанов 6f05877ac9 Исключения
Сделал небольшую доработку по исключениям.
1. Создал новое исключение, которое позволяет указывать сразу несколько невалидных параметров.
2. Поправил middleware, сделал обобщённый класс, который преобразует исключение.
2023-06-28 16:18:29 +05:00

71 lines
2.5 KiB
C#

using AsbCloudApp.Exceptions;
using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Threading.Tasks;
using AsbCloudApp.Exceptions.Interfaces;
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);
}
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);
}
catch (ArgumentsInvalidException ex)
{
Console.WriteLine($"ArgumentExceptions 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);
}
catch (ForbidException ex)
{
Console.WriteLine($"ForbidException in {context.Request.Method}: {ex.Message}");
context.Response.Clear();
context.Response.StatusCode = 403;
}
catch (TaskCanceledException ex)
{
Console.WriteLine(ex.Message);
}
catch (Exception ex) // TODO: find explicit exception. Use Trace. Add body size to message.
{
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<TException>(TException ex)
where TException: Exception, IHasValidation
{
object error = ex.ToValidationErrorObject();
var buffer = System.Text.Json.JsonSerializer.Serialize(error);
return buffer;
}
}
}