mirror of
https://github.com/PluralKit/PluralKit.git
synced 2026-02-04 04:56:49 +00:00
feat(apiv2): better model validation error UX
This commit is contained in:
parent
5add31c77e
commit
098d804344
15 changed files with 247 additions and 186 deletions
|
|
@ -1,7 +1,10 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
using PluralKit.Core;
|
||||
|
||||
namespace PluralKit.API
|
||||
{
|
||||
public class PKError: Exception
|
||||
|
|
@ -25,15 +28,49 @@ namespace PluralKit.API
|
|||
|
||||
public class ModelParseError: PKError
|
||||
{
|
||||
public ModelParseError() : base(400, 40001, "Error parsing JSON model")
|
||||
private IEnumerable<ValidationError> _errors { get; init; }
|
||||
public ModelParseError(IEnumerable<ValidationError> errors) : base(400, 40001, "Error parsing JSON model")
|
||||
{
|
||||
// todo
|
||||
_errors = errors;
|
||||
}
|
||||
|
||||
public new JObject ToJson()
|
||||
{
|
||||
var j = base.ToJson();
|
||||
var e = new JObject();
|
||||
|
||||
foreach (var err in _errors)
|
||||
{
|
||||
var o = new JObject();
|
||||
|
||||
if (err is FieldTooLongError fe)
|
||||
{
|
||||
o.Add("message", $"Field {err.Key} is too long.");
|
||||
o.Add("actual_length", fe.ActualLength);
|
||||
o.Add("max_length", fe.MaxLength);
|
||||
}
|
||||
else if (err.Text != null)
|
||||
o.Add("message", err.Text);
|
||||
else
|
||||
o.Add("message", $"Field {err.Key} is invalid.");
|
||||
|
||||
if (e[err.Key] != null)
|
||||
{
|
||||
if (e[err.Key].Type == JTokenType.Object)
|
||||
{
|
||||
var current = e[err.Key];
|
||||
e.Remove(err.Key);
|
||||
e.Add(err.Key, new JArray());
|
||||
(e[err.Key] as JArray).Add(current);
|
||||
}
|
||||
|
||||
(e[err.Key] as JArray).Add(o);
|
||||
}
|
||||
else
|
||||
e.Add(err.Key, o);
|
||||
}
|
||||
|
||||
j.Add("errors", e);
|
||||
return j;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue