fix(api): send proper content-type header for errors

This commit is contained in:
spiral 2022-06-10 16:44:04 -04:00
parent cbef15eaa2
commit 0f47042dd1
No known key found for this signature in database
GPG Key ID: 244A11E4B0BCF40E
2 changed files with 13 additions and 16 deletions

View File

@ -1,3 +1,5 @@
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
@ -37,6 +39,13 @@ public static class APIJsonExt
return o;
}
public static async Task WriteJSON(this HttpResponse resp, int statusCode, string jsonText)
{
resp.StatusCode = statusCode;
resp.Headers.Add("content-type", "application/json");
await resp.WriteAsync(jsonText);
}
}
public struct FrontersReturnNew

View File

@ -107,31 +107,19 @@ public class Startup
// handle common ISEs that are generated by invalid user input
if (exc.Error.IsUserError())
{
ctx.Response.StatusCode = 400;
await ctx.Response.WriteAsync("{\"message\":\"400: Bad Request\",\"code\":0}");
}
await ctx.Response.WriteJSON(400, "{\"message\":\"400: Bad Request\",\"code\":0}");
else if (exc.Error is not PKError)
{
ctx.Response.StatusCode = 500;
await ctx.Response.WriteAsync("{\"message\":\"500: Internal Server Error\",\"code\":0}");
}
await ctx.Response.WriteJSON(500, "{\"message\":\"500: Internal Server Error\",\"code\":0}");
// for some reason, if we don't specifically cast to ModelParseError, it uses the base's ToJson method
else if (exc.Error is ModelParseError fe)
{
ctx.Response.StatusCode = fe.ResponseCode;
await ctx.Response.WriteAsync(JsonConvert.SerializeObject(fe.ToJson()));
}
await ctx.Response.WriteJSON(fe.ResponseCode, JsonConvert.SerializeObject(fe.ToJson()));
else
{
var err = (PKError)exc.Error;
ctx.Response.StatusCode = err.ResponseCode;
var json = JsonConvert.SerializeObject(err.ToJson());
await ctx.Response.WriteAsync(json);
await ctx.Response.WriteJSON(err.ResponseCode, JsonConvert.SerializeObject(err.ToJson()));
}
await ctx.Response.CompleteAsync();