Files
server/src/Api/Models/Public/Response/ErrorResponseModel.cs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

79 lines
2.4 KiB
C#
Raw Normal View History

using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
2021-12-14 15:05:07 +00:00
using Microsoft.AspNetCore.Mvc.ModelBinding;
2021-12-14 15:05:07 +00:00
namespace Bit.Api.Models.Public.Response;
2022-08-29 16:06:55 -04:00
public class ErrorResponseModel : IResponseModel
{
public ErrorResponseModel(string message)
{
Message = message;
}
public ErrorResponseModel(ModelStateDictionary modelState)
{
Message = "The request's model state is invalid.";
Errors = new Dictionary<string, IEnumerable<string>>();
var keys = modelState.Keys.ToList();
var values = modelState.Values.ToList();
for (var i = 0; i < values.Count; i++)
2022-08-29 16:06:55 -04:00
{
var value = values[i];
if (keys.Count <= i)
{
// Keys not available for some reason.
break;
}
var key = keys[i];
if (value.ValidationState != ModelValidationState.Invalid || value.Errors.Count == 0)
2022-08-29 16:06:55 -04:00
{
continue;
}
var errors = value.Errors.Select(e => e.ErrorMessage);
Errors.Add(key, errors);
2022-08-29 16:06:55 -04:00
}
}
public ErrorResponseModel(Dictionary<string, IEnumerable<string>> errors)
: this("Errors have occurred.", errors)
{ }
public ErrorResponseModel(string errorKey, string errorValue)
: this(errorKey, [errorValue])
{ }
public ErrorResponseModel(string errorKey, IEnumerable<string> errorValues)
: this(new Dictionary<string, IEnumerable<string>> { { errorKey, errorValues } })
{ }
2022-08-29 14:53:16 -04:00
[JsonConstructor]
public ErrorResponseModel(string message, Dictionary<string, IEnumerable<string>> errors)
{
Message = message;
Errors = errors;
}
2022-08-29 16:06:55 -04:00
/// <summary>
/// String representing the object's type. Objects of the same type share the same properties.
/// </summary>
/// <example>error</example>
[Required]
public string Object => "error";
/// <summary>
/// A human-readable message providing details about the error.
/// </summary>
/// <example>The request model is invalid.</example>
[Required]
public string Message { get; init; }
/// <summary>
/// If multiple errors occurred, they are listed in dictionary. Errors related to a specific
/// request parameter will include a dictionary key describing that parameter.
/// </summary>
public Dictionary<string, IEnumerable<string>>? Errors { get; }
}