Sha256: 0801d563fa78f863b3da96d106d955a7925eecfb4edd2e4f01ef843a035effa4

Contents?: true

Size: 1.57 KB

Versions: 3

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 sauvegarder 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

3 entries across 3 versions & 1 rubygems

Version Path
captive-api-0.2.12 app/controllers/concerns/api/render_error_concern.rb
captive-api-0.2.11 app/controllers/concerns/api/render_error_concern.rb
captive-api-0.2.9 app/controllers/concerns/api/render_error_concern.rb