Commit 54a56e4
committed
chore: fix error serialization for string errors
When adding custom validation errors, Rails allows both Symbols and
Strings:
```
class Foo < ActiveRecord::Base
validate :add_symbol_error
validate :add_string_error
def add_symbol_error
errors.add(:title, :too_short)
end
def add_string_error
errors.add(:title, 'is too short')
end
end
```
The Symbol error will later be translated by Rails using the i18n logic,
when calling `foo.errors.full_messages` or similar methods. The String
error will stay as it is.
see https://api.rubyonrails.org/v7.0.8.7/classes/ActiveModel/Errors.html#method-i-add
This commit introduces support for these String errors in the error
serialization class.
Before this change, the error response for the validation that was
added in the specs looked like this:
```ruby
[
{
"status"=>"422",
"source"=>{"pointer"=>"/data/attributes/title"},
"title"=>"Unprocessable Entity",
"detail"=> "Title translation missing: en.activerecord.errors.models.note.attributes.title.is not so nice",
"code"=>"is_not_so_nice"
}
]
```
Please note the "translation missing" part in the `detail`, and the
`code` that is a parameterized version of the String error.
After this change, the error response looks like this:
```ruby
[
{
"status"=>"422",
"source"=>{"pointer"=>"/data/attributes/title"},
"title"=>"Unprocessable Entity",
"detail"=>"Title is not so nice",
"code"=>"invalid"
}
]
```
The `detail` is now the String error as passed in by Rails, and the
`code` is a generic `"invalid"` one.1 parent 6ff33ee commit 54a56e4
3 files changed
Lines changed: 48 additions & 4 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
13 | 13 | | |
14 | 14 | | |
15 | 15 | | |
16 | | - | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
17 | 19 | | |
18 | 20 | | |
19 | 21 | | |
| |||
29 | 31 | | |
30 | 32 | | |
31 | 33 | | |
32 | | - | |
33 | | - | |
34 | | - | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
35 | 43 | | |
36 | 44 | | |
37 | 45 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
43 | 43 | | |
44 | 44 | | |
45 | 45 | | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
46 | 61 | | |
47 | 62 | | |
48 | 63 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
119 | 119 | | |
120 | 120 | | |
121 | 121 | | |
| 122 | + | |
| 123 | + | |
| 124 | + | |
| 125 | + | |
| 126 | + | |
| 127 | + | |
| 128 | + | |
| 129 | + | |
| 130 | + | |
| 131 | + | |
| 132 | + | |
| 133 | + | |
| 134 | + | |
| 135 | + | |
| 136 | + | |
| 137 | + | |
| 138 | + | |
| 139 | + | |
| 140 | + | |
| 141 | + | |
| 142 | + | |
122 | 143 | | |
123 | 144 | | |
124 | 145 | | |
| |||
0 commit comments