Sha256: f76797987ab3e317a2d3f13e2063940b8e1fe4484167ea172e259bf546130579

Contents?: true

Size: 1.69 KB

Versions: 3

Compression:

Stored size: 1.69 KB

Contents

module TbCore
  module ErrorHandling
    extend ActiveSupport::Concern

    included do
      rescue_from RequestError, with: :handle_request_error
      rescue_from ActiveRecord::RecordNotFound, with: :handle_record_not_found
      rescue_from ActionController::UnknownFormat, with: :handle_unknown_format_error
    end

    def handle_request_error(error)
      error.request_url = request.original_url
      error.template = template_for_request_error() if respond_to?(:template_for_request_error, true)

      if error.is_a?(UnauthorizedError) && request.format.html?
        redirect_to(login_path_for_require_user)
        return false
      end

      do_error_response(error)
    end

    def do_error_response(error)
      respond_to do |format|
        format.json { render json: { errors: error.message }, status: error.code }
        format.xml { render xml: { errors: error.message }, status: error.code }
        format.all do
          @error = error
          render template: error.template,
                 layout: nil,
                 formats: [:html],
                 status: error.code,
                 content_type: 'text/html'
        end
      end
    end

    def handle_record_not_found(exception)
      error = NotFoundError.new(class_string(exception.model))
      handle_request_error(error)
    end

    def class_string(model_name)
      string = 'record'
      begin
        object_class = Object.const_get(model_name)
        string = object_class.model_name.human
      rescue NameError # rubocop:disable Lint/HandleExceptions
      end
      string
    end

    def handle_unknown_format_error(_exception)
      error = NotFoundError.new
      handle_request_error(error)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
tb_core-1.4.8 app/controllers/concerns/tb_core/error_handling.rb
tb_core-1.4.7 app/controllers/concerns/tb_core/error_handling.rb
tb_core-1.4.6 app/controllers/concerns/tb_core/error_handling.rb