forked from ddrilling/AsbCloudServer
Handle ArgumentException in SimplifyExceptionsMiddleware. It replaces StatusCode 500 (server error) to StatusCode 400 (bad request)
This commit is contained in:
parent
e29dbf49df
commit
9233b45966
@ -1,5 +1,6 @@
|
|||||||
using Microsoft.AspNetCore.Http;
|
using Microsoft.AspNetCore.Http;
|
||||||
using System;
|
using System;
|
||||||
|
using System.IO;
|
||||||
using System.Threading.Tasks;
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
namespace AsbCloudWebApi.Middlewares
|
namespace AsbCloudWebApi.Middlewares
|
||||||
@ -19,6 +20,15 @@ namespace AsbCloudWebApi.Middlewares
|
|||||||
{
|
{
|
||||||
await next?.Invoke(context);
|
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)
|
catch (TaskCanceledException ex)
|
||||||
{
|
{
|
||||||
Console.WriteLine(ex.Message);
|
Console.WriteLine(ex.Message);
|
||||||
@ -31,5 +41,12 @@ namespace AsbCloudWebApi.Middlewares
|
|||||||
throw;
|
throw;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private 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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user