question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to support JSON API Error Objects?

See original GitHub issue

JSON API specifies a format for so-called “error objects”. While I could create such error documents myself, I would be interested to see what would be needed to support creating such documents based on ModelState validation.

An example from the JSON API site:

HTTP/1.1 422 Unprocessable Entity
Content-Type: application/vnd.api+json

{
  "jsonapi": { "version": "1.0" },
  "errors": [
    {
      "code":   "123",
      "source": { "pointer": "/data/attributes/firstName" },
      "title":  "Value is too short",
      "detail": "First name must contain at least three characters."
    },
    {
      "code":   "225",
      "source": { "pointer": "/data/attributes/password" },
      "title": "Passwords must contain a letter, number, and punctuation character.",
      "detail": "The password provided is missing a punctuation character."
    },
    {
      "code":   "226",
      "source": { "pointer": "/data/attributes/password" },
      "title": "Password and password confirmation do not match."
    }
  ]
}

For reference, the default output of ModelState looks like this:

if (!ModelState.IsValid)
    throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
{
    "Message": "The request is invalid.",
    "ModelState": {
        "category.Name": [
            "The field Name must be a string or array type with a minimum length of '20'."
        ]
    }
}

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:2
  • Comments:8

github_iconTop GitHub Comments

2reactions
lrfahmicommented, Apr 19, 2020

How to use error response in asp.net core web api?

1reaction
rbonestellcommented, Jul 13, 2021

Checking in another year later, has anyone accomplished supporting JSON:API serialization of ASP.NET model validation errors to JSON:API error objects?

Update!

For anyone else looking to support JSON:API format for ASP.NET validation responses using this JsonApiSerializer library, here’s how I’ve accomplished that goal in ASP.NET Core 5:

  1. Disable ASP.NET ApiController’s implicit model state validation in Startup.ConfigureServices(): services.Configure<ApiBehaviorOptions>(options => { options.SuppressModelStateInvalidFilter = true; });
  2. Create a new custom ActionFilterAttribute:
public class JsonApiValidationFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        if (!context.ModelState.IsValid)
        {
            DocumentRoot<string> response = new()
            {
                Errors = context.ModelState
                    .SelectMany(ms => ms.Value.Errors, (ms, mse) =>
                        new Error()
                        {
                            Detail = mse.ErrorMessage,
                            Status = "400",
                            Title = "Validation error"
                        }).ToList()
            };
            context.Result = new BadRequestObjectResult(response);
        }
        base.OnActionExecuting(context);
    }
}
  1. Add your new [JsonApiValidationFilter] attribute to your JSON:API-friendly controller classes.
Read more comments on GitHub >

github_iconTop Results From Across the Web

JSON:API — Latest Specification (v1.1)
A JSON object MUST be at the root of every JSON:API request and response document containing data. This object defines a document's “top...
Read more >
Handling API errors with Problem JSON
Celonis Senior Software Engineer David Hettler explains how Celonis leverages Problem JSON to solve API error handling once and for all.
Read more >
JSON API Error Object
// creating a new Error Object: $error = new JsonApiErrorObject(); // set some known data about the error: $error->setTitle(new LangText('LBL_ERROR_LABEL_TITLE ...
Read more >
REST API error handling
The REST API reports errors by returning an appropriate HTTP response code, for example 404 (Not Found), and a JSON response. Any HTTP...
Read more >
Is there any standard for JSON API response format?
Use HTTP Status + json body (even if it is an error). Define a uniform structure for errors (ex: code, message, reason, type,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found