about summary refs log tree commit diff
path: root/app/lib/validation_error_formatter.rb
diff options
context:
space:
mode:
authorEugen Rochko <eugen@zeonfederated.com>2021-03-01 04:59:13 +0100
committerGitHub <noreply@github.com>2021-03-01 04:59:13 +0100
commit9aa37b32c3307dcb5896e1b768967666a6fdbf65 (patch)
treed10630dcc1a46d450be7b711e9ae47c91492d2cf /app/lib/validation_error_formatter.rb
parentb4cb8c3c8356e226061fd70ae2139318c6a558e5 (diff)
Add `details` to error response for `POST /api/v1/accounts` in REST API (#15803)
Diffstat (limited to 'app/lib/validation_error_formatter.rb')
-rw-r--r--app/lib/validation_error_formatter.rb32
1 files changed, 32 insertions, 0 deletions
diff --git a/app/lib/validation_error_formatter.rb b/app/lib/validation_error_formatter.rb
new file mode 100644
index 000000000..3f964f739
--- /dev/null
+++ b/app/lib/validation_error_formatter.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+class ValidationErrorFormatter
+  def initialize(error, aliases = {})
+    @error   = error
+    @aliases = aliases
+  end
+
+  def as_json
+    { error: @error.to_s, details: details }
+  end
+
+  private
+
+  def details
+    h = {}
+
+    errors.details.each_pair do |attribute_name, attribute_errors|
+      messages = errors.messages[attribute_name]
+
+      h[@aliases[attribute_name] || attribute_name] = attribute_errors.map.with_index do |error, index|
+        { error: 'ERR_' + error[:error].to_s.upcase, description: messages[index] }
+      end
+    end
+
+    h
+  end
+
+  def errors
+    @errors ||= @error.record.errors
+  end
+end