Sha256: 40e3b4ba891afbe418008cfb7c6dbff66c58211ab74d454292374155c6d7082f

Contents?: true

Size: 1.24 KB

Versions: 1

Compression:

Stored size: 1.24 KB

Contents

# frozen_string_literal: true

require "pry"

module MinatoErrorHandler
  module ErrorHandler
    extend ActiveSupport::Concern

    included do |base|
      rescue_from StandardError, with: :handle

      base.extend ClassMethods
    end

    private

    def handle(exception)
      error = parse_error(exception)
      report_error(error)
      render json: { errors: [error.as_json] }, status: error.status_code
    end

    def parse_error(error)
      return error if error.is_a?(MinatoErrorHandler::MinatoError)

      error_class = self.class.default_error_class || MinatoErrorHandler::UnknowError

      minato_error = error_class.new
      minato_error.caused_by = error.full_message
      minato_error.set_backtrace(error.backtrace)
      minato_error
    end

    def report_error(error)
      Rails.logger.error(error.as_json)
    end

    module ClassMethods
      def default_error(klass)
        # rubocop:disable Style/ClassVars
        class_variable_set(:@@default_error_class, klass.to_s.camelize.constantize)
        # rubocop:enable Style/ClassVars
      end

      def default_error_class
        return nil unless class_variable_defined? :@@default_error_class

        class_variable_get(:@@default_error_class)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
minato_error_handler-0.1.2.pre.3 lib/minato_error_handler/error_handler.rb