[backend/middleware] Make validation errors compliant with (Mastodon)ErrorResponse schemas
This commit is contained in:
parent
08cd1f2c66
commit
5c5e724fd3
2 changed files with 26 additions and 1 deletions
|
@ -1,6 +1,9 @@
|
|||
using System.Buffers;
|
||||
using System.Net;
|
||||
using System.Text.Encodings.Web;
|
||||
using System.Text.Json;
|
||||
using Iceshrimp.Backend.Controllers.Attributes;
|
||||
using Iceshrimp.Backend.Core.Middleware;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.Formatters;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
|
@ -55,4 +58,25 @@ public static class MvcBuilderExtensions
|
|||
|
||||
return builder;
|
||||
}
|
||||
|
||||
public static IMvcBuilder AddApiBehaviorOptions(this IMvcBuilder builder)
|
||||
{
|
||||
builder.ConfigureApiBehaviorOptions(o =>
|
||||
{
|
||||
o.InvalidModelStateResponseFactory = actionContext =>
|
||||
{
|
||||
var details = new ValidationProblemDetails(actionContext.ModelState);
|
||||
|
||||
var status = (HttpStatusCode?)details.Status ?? HttpStatusCode.BadRequest;
|
||||
var message = details.Title ?? "One or more validation errors occurred.";
|
||||
if (details.Detail != null)
|
||||
message += $" - {details.Detail}";
|
||||
var errors = JsonSerializer.Serialize(details.Errors);
|
||||
|
||||
throw new GracefulException(status, status.ToString(), message, errors);
|
||||
};
|
||||
});
|
||||
|
||||
return builder;
|
||||
}
|
||||
}
|
|
@ -11,7 +11,8 @@ builder.Services.AddControllers()
|
|||
.AddNewtonsoftJson() //TODO: remove once dotNetRdf switches to System.Text.Json (or we switch to LinkedData.NET)
|
||||
.AddMultiFormatter()
|
||||
.AddModelBindingProviders()
|
||||
.AddValueProviderFactories();
|
||||
.AddValueProviderFactories()
|
||||
.AddApiBehaviorOptions();
|
||||
|
||||
builder.Services.AddSwaggerGenWithOptions();
|
||||
builder.Services.AddLogging(logging => logging.AddCustomConsoleFormatter());
|
||||
|
|
Loading…
Add table
Reference in a new issue