Return errors as json objects instead of strings#722
Conversation
chvp
left a comment
There was a problem hiding this comment.
Did we ever talk about this in person? The one thing I find a bit icky about this is that this basically exposes the rails way of handling errors to the clients. IMO, it should always be theoretically possible to create another API without too much issues.
IIRC: we said have some way of providing more structured errors to clients, but to add some layer to convert rails' structure to something else ERROR_TYPE_MAP = {
blank: :required,
taken: :not_unique
}
def transform_error_for_json(error)
result = { attribute: error.attribute, type: ERROR_TYPE_MAP[error.type] }
result[:options] = error.options.except(*ActiveModel::Error::CALLBACKS_OPTIONS, *ActiveModel::Error::MESSAGE_OPTIONS)
result
endMaybe we should just be more explicit about which other options we include? (Rather than including everything except some specific things). def transform_error_for_json(error)
result = %i[attribute type].index_with { |it| error.send(it) }
result[:options] = error.options.slice(:count, :other_option)
result
end |
This options seems fine to me. |
We currently have a mapping in
config/locales/en.ymlto convert error messages to keys, which we then look up in web's translations. I realised that by using@object.errors.errorswe can just directly return the attributes of each error.A response with errors would then become:
Options can be filled with more detail if needed. (For example, if we would have length validations: `{"attribute" => "title", "type" => "too_long", "options" => { "count" => 50 }
@chvp What do you think? Wanted to check this principle first, before I update the controllers, and js-client and web.