-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathvalidation_errors.rb
53 lines (45 loc) · 1.15 KB
/
validation_errors.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# frozen_string_literal: true
module Grape
module Exceptions
class ValidationErrors < Base
ERRORS_FORMAT_KEY = 'grape.errors.format'
DEFAULT_ERRORS_FORMAT = '%<attributes>s %<message>s'
include Enumerable
attr_reader :errors
def initialize(errors: [], headers: {})
@errors = errors.group_by(&:params)
super(message: full_messages.join(', '), status: 400, headers: headers)
end
def each
errors.each_pair do |attribute, errors|
errors.each do |error|
yield attribute, error
end
end
end
def as_json(**_opts)
errors.map do |k, v|
{
params: k,
messages: v.map(&:to_s)
}
end
end
def to_json(*_opts)
as_json.to_json
end
def full_messages
messages = map do |attributes, error|
I18n.t(
ERRORS_FORMAT_KEY,
default: DEFAULT_ERRORS_FORMAT,
attributes: translate_attributes(attributes),
message: error.message
)
end
messages.uniq!
messages
end
end
end
end