Sunday, June 19, 2016

Json API Error Codes


The code member of an error object contains an application-specific code representing the type of problem encountered. code is similar to title in that both identify a general type of problem (unlike detail, which is specific to the particular instance of the problem), but dealing with code is easier programatically, because the “same” title may appear in different forms due to localization. For the example below, imagine the API docs specifed the following mapping:
Code Problem
123 Value too short
225 Password lacks a letter, number, or punctuation character
226 Passwords do not match
227 Password cannot be one of last five passwords
Multiple errors on "password" attribute, with error code:
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/vnd.api+json

{
  "jsonapi": { "version": "1.0" },
  "errors": [
    {
      "code":   "123",
      "source": { "pointer": "/data/attributes/first-name" },
      "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."
    }
  ]
}
Notice that this response includes not only the errors top-level member, but the jsonapi top-level member. Error responses may not contain the top-level data member, but can include all the other top-level members JSON API defines.
Also, notice that the third error object lacks a detail member (perhaps for security). Again, all error object members are optional.

No comments: