Skip to content

Serialize ActiveModel error keys in the error payload #11

@Startouf

Description

@Startouf

There is currently no serialization at all of specific ActiveModel error keys/codes in the jsonapi error payload (only the human friendly translated messages). This makes it impossible for the frontend to recognize exactly the error and behave accordingly, since there is no programmer friendly error string in the payload.

According to http://jsonapi.org/format/#errors-processing, the "code" attribute in the error payload should be an application-specific code, whereas the one currently serialized by jsonapi actually correspond to the http_status_code translated

I would suggest using activemodel error keys (eventually with some prefix) instead

Assume I have the following model with errors

#<ActiveModel::Errors:0x007fdf455ff308
 @base=...
 @details=
  {:email=>[{:error=>:blank}],
   :password=>[{:error=>:blank}],
   :first_name=>[{:error=>:blank, :minimum=>2}],
   :last_name=>[{:error=>:blank, :minimum=>2}]},
 @messages=
  {:email=>["doit être rempli(e)"], :password=>["doit être rempli(e)"], :first_name=>["doit être rempli(e)"], :last_name=>["doit être rempli(e)"]}>

The current serialization would throw errors like

        {
            "code": "unprocessable_entity",
            "status": "422",
            "title": "Validation Error",
            "detail": "Email : doit être rempli",
            "source": {
                "pointer": "/data/attributes/email"
            },
            "meta": {
                "attribute": "email",
                "message": ": doit être rempli(e)"
            }
        }

Suppose I have, in addition to the previous one, a different message on the same attribute but with a different error (like a minimum length of 3). then it is difficult to distinguish both errors, or we'd have to rely on the french human translation.

I would rather serialize the ActiveModel using a code that looks like

        {
            "code": "activemodel_validation_blank",
            ...
        }

Or, at least, serialize the error code in the meta attributes

"meta": {
                "attribute": "email",
                "message": ": doit être rempli(e)"
                "code": "blank"
            }

What do you think ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions