Sha256: 04d7fad8970798319f6ef833c4bf726d146e0b773b90b1b97aebf3a69c77b161

Contents?: true

Size: 1.91 KB

Versions: 1

Compression:

Stored size: 1.91 KB

Contents

module PipeRpc
  class ErrorResponse
    def initialize(args = {})
      @id = args.fetch(:id, nil)
      error = args.fetch(:error)
      @code = error.fetch(:code)
      @message = msg_for(@code) || error.fetch(:message, 'Unknown error')
      @data = error.fetch(:data, nil)
    end

    attr_reader :id, :code, :message, :data

    def to_h
      { id: id, error: { code: code, message: message, data: data } }
    end

    def native_error(request = nil)
      @request = request
      error_for(@code)
    end

    def result_for(*args)
      native_error(*args)
    end

    private

    def msg_for(code)
      case code
      when -32700 then 'Parse error'
      when -32600 then 'Invalid Request'
      when -32601 then 'Method not found'
      when -32602 then 'Invalid arguments'
      when -32603 then 'Internal error'
      when -32604 then 'Server not found'
      when -32605 then 'Reflected error'
      else nil
      end
    end

    def error_for(code)
      case code
      when -32601 then no_method_error
      when -32602 then argument_error
      when -32604 then no_server_error
      when -32605 then reflected_error
      else internal_error
      end
    end

    def no_method_error
      method = @data.fetch(:method)
      args = @data.fetch(:args)
      NoMethodError.new("undefined method `#{method}' for <Client:#{@request.server}>", method, args)
    end

    def argument_error
      ArgumentError.new(@data.fetch(:message))
    end

    def no_server_error
      NoServerError.new("undefined server `#{@request.server}'")
    end

    def internal_error
      InternalError.new("#{@data[:message]}").tap do |error|
        error.set_backtrace(@data[:backtrace]) if error.respond_to? :set_backtrace
      end
    end

    def reflected_error
      ReflectedError.new("#{@data[:message]}").tap do |error|
        error.set_backtrace(@data[:backtrace]) if error.respond_to? :set_backtrace
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
pipe_rpc-0.2.0 lib/pipe_rpc/error_response.rb