Sha256: 72f3d8335e8b847ac719082ce73698755aed24e217bdf5dc1c2247409c4e9271

Contents?: true

Size: 1.57 KB

Versions: 8

Compression:

Stored size: 1.57 KB

Contents

# frozen_string_literal: true

module API
  ##
  # Permet de catcher des erreurs pour rendre une page d'erreur en json
  module RenderErrorConcern
    extend ActiveSupport::Concern

    included do
      rescue_from ActiveRecord::RecordNotFound, with: :not_found
      rescue_from ActionController::ParameterMissing, with: :handle_parameter_missing

      rescue_from CanCan::AccessDenied do |exception|
        render_error_from_exception(exception, status: :forbidden)
      end

      protected

      def render_error_from_object(
        object,
        status: :unprocessable_entity,
        message: "Erreur de validation"
      )
        errors = object.errors.messages
        Rails.logger.error("Impossible de sauvagarder l'objet #{object.class} : #{errors}")
        render_error(
          message: message, errors: errors, status: status
        )
      end

      def render_error_from_exception(exception, status:, message: nil)
        render_error(
          message: exception.message, errors: exception.message, status: status
        )
      end

      def handle_parameter_missing(exception)
        render_error_from_exception(exception, status: :bad_request)
      end

      def not_found(exception)
        render_error(message: "#{exception.model} not found", status: :not_found)
      end

      def render_error(message:, status:, errors: [], code: nil)
        code ||= status.to_s
        render json: {
                 message: message,
                 errors: errors,
                 code: code,
               },
               status: status
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
captive-api-0.2.8 app/controllers/concerns/api/render_error_concern.rb
captive-api-0.2.7 app/controllers/concerns/api/render_error_concern.rb
captive-api-0.2.6 app/controllers/concerns/api/render_error_concern.rb
captive-api-0.2.5 app/controllers/concerns/api/render_error_concern.rb
captive-api-0.2.4 app/controllers/concerns/api/render_error_concern.rb
captive-api-0.2.3 app/controllers/concerns/api/render_error_concern.rb
captive-api-0.2.2 app/controllers/concerns/api/render_error_concern.rb
captive-api-0.1.0.alpha app/controllers/concerns/api/render_error_concern.rb