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

53 lines
1.7 KiB
C#
Raw Normal View History

using Microsoft.AspNetCore.Http;
using System;
using System.IO;
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);
}
catch(ArgumentException 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 (TaskCanceledException ex)
{
Console.WriteLine(ex.Message);
}
catch(Exception ex)
{
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;
}
}
2021-12-23 18:07:20 +05:00
private static string MakeJsonBody(ArgumentException ex)
{
object error = new { name = ex.ParamName, errors = new string[] { ex.Message } };
var buffer = System.Text.Json.JsonSerializer.Serialize(error);
return buffer;
}
}
}