Sha256: 00433c23a63bb82d8463082a641cbcdf8e1071ffddce0361b483998636d7a7cb

Contents?: true

Size: 1.72 KB

Versions: 5

Compression:

Stored size: 1.72 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],
                 locals: { },
                 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

5 entries across 5 versions & 1 rubygems

Version Path
tb_core-1.5.4 app/controllers/concerns/tb_core/error_handling.rb
tb_core-1.5.3 app/controllers/concerns/tb_core/error_handling.rb
tb_core-1.5.2 app/controllers/concerns/tb_core/error_handling.rb
tb_core-1.5.1 app/controllers/concerns/tb_core/error_handling.rb
tb_core-1.5.0 app/controllers/concerns/tb_core/error_handling.rb