Sha256: 6a634175f2a5ad273ab93889dd9c487332da5202ebd1e0a3bb4cb4e3cd4906d3

Contents?: true

Size: 1.35 KB

Versions: 7

Compression:

Stored size: 1.35 KB

Contents

# frozen_string_literal: true

require 'grape/exceptions/base'

module Grape
  module Exceptions
    class ValidationErrors < Grape::Exceptions::Base
      ERRORS_FORMAT_KEY = 'grape.errors.format'
      DEFAULT_ERRORS_FORMAT = '%{attributes} %{message}'

      include Enumerable

      attr_reader :errors

      def initialize(errors: [], headers: {}, **_options)
        @errors = {}
        errors.each do |validation_error|
          @errors[validation_error.params] ||= []
          @errors[validation_error.params] << validation_error
        end

        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

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
grape-1.7.1 lib/grape/exceptions/validation_errors.rb
grape-1.7.0 lib/grape/exceptions/validation_errors.rb
grape-1.6.2 lib/grape/exceptions/validation_errors.rb
grape-1.6.1 lib/grape/exceptions/validation_errors.rb
grape-1.6.0 lib/grape/exceptions/validation_errors.rb
grape-1.5.3 lib/grape/exceptions/validation_errors.rb
grape-1.5.2 lib/grape/exceptions/validation_errors.rb