Exception: JSON_RPC::JsonRpcError

Inherits:
StandardError
  • Object
show all
Defined in:
lib/json_rpc/json_rpc_error.rb

Overview

Custom exception class for JSON-RPC errors, based on the JSON-RPC 2.0 specification.

Constant Summary collapse

ERROR_CODES =

Define the standard JSON-RPC 2.0 error codes

{
  parse_error: {
    code: -32_700,
    message: "Parse error"
  },
  invalid_request: {
    code: -32_600,
    message: "Invalid Request"
  },
  method_not_found: {
    code: -32_601,
    message: "Method not found"
  },
  invalid_params: {
    code: -32_602,
    message: "Invalid params"
  },
  internal_error: {
    code: -32_603,
    message: "Internal error"
  },
  # Implementation-defined server-errors -32000 to -32099
  server_error: {
    code: -32_000,
    message: "Server error"
  }
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(symbol, message: nil, data: nil) ⇒ JsonRpcError

Initialize the error using a symbol key, with optional custom message and data.



74
75
76
77
78
79
# File 'lib/json_rpc/json_rpc_error.rb', line 74

def initialize(symbol, message: nil, data: nil)
  error_details = self.class.build(symbol, message: message, data: data)
  @code = error_details[:code]
  @data = error_details[:data]
  super(error_details[:message])
end

Instance Attribute Details

#codeInteger, Object (readonly)



37
38
39
# File 'lib/json_rpc/json_rpc_error.rb', line 37

def code
  @code
end

#dataInteger, Object (readonly)



37
38
39
# File 'lib/json_rpc/json_rpc_error.rb', line 37

def data
  @data
end

Class Method Details

.[](symbol) ⇒ Hash

Retrieve error details by symbol.

Raises:

  • (ArgumentError)

    if the error code is unknown.



44
45
46
# File 'lib/json_rpc/json_rpc_error.rb', line 44

def self.[](symbol)
  ERROR_CODES[symbol] or raise ArgumentError, "Unknown error symbol: #{symbol}"
end

.build(symbol, message: nil, data: nil) ⇒ Hash

Build an error hash, allowing custom message or data to override defaults.



62
63
64
65
66
67
# File 'lib/json_rpc/json_rpc_error.rb', line 62

def self.build(symbol, message: nil, data: nil)
  error = self[symbol].dup
  error[:message] = message if message
  error[:data] = data if data
  error
end

.find_by_code(code) ⇒ Hash?

Retrieve error details by code.



52
53
54
# File 'lib/json_rpc/json_rpc_error.rb', line 52

def self.find_by_code(code)
  ERROR_CODES.values.find { |details| details[:code] == code }
end

Instance Method Details

#as_jsonObject

For ActiveSupport::JSON



91
# File 'lib/json_rpc/json_rpc_error.rb', line 91

def as_json(*) = to_h

#to_hHash

Returns a hash formatted for a JSON-RPC error response object (the value of the ‘error’ key).



84
85
86
87
88
# File 'lib/json_rpc/json_rpc_error.rb', line 84

def to_h
  hash = { code: code, message: message }
  hash[:data] = data if data
  hash
end