class Twirp::Error

Twirp::Error represents an error response from a Twirp service. Twirp::Error is not an Exception to be raised, but a value to be returned by service handlers and received by clients.

Attributes

cause[RW]
code[R]
meta[R]
msg[R]

Public Class Methods

internal_with(err) click to toggle source

Wrap another error as a Twirp::Error :internal.

# File lib/twirp/error.rb, line 64
def self.internal_with(err)
  twerr = internal err.message, cause: err.class.name
  twerr.cause = err # availabe in error hook for inspection, but not in the response
  twerr
end
new(code, msg, meta=nil) click to toggle source

Initialize a Twirp::Error The code must be one of the valid ERROR_CODES Symbols (e.g. :internal, :not_found, :permission_denied …). The msg is a String with the error message. The meta is optional error metadata, if included it must be a Hash with String values.

# File lib/twirp/error.rb, line 78
def initialize(code, msg, meta=nil)
  @code = code.to_sym
  @msg = msg.to_s
  @meta = validate_meta(meta)
end
valid_code?(code) click to toggle source
# File lib/twirp/error.rb, line 49
def self.valid_code?(code)
  ERROR_CODES_TO_HTTP_STATUS.key? code # one of the valid symbols
end

Public Instance Methods

inspect() click to toggle source
# File lib/twirp/error.rb, line 98
def inspect
  to_s
end
to_h() click to toggle source

Key-value representation of the error. Can be directly serialized into JSON.

# File lib/twirp/error.rb, line 85
def to_h
  h = {
    code: @code,
    msg: @msg,
  }
  h[:meta] = @meta unless @meta.empty?
  h
end
to_s() click to toggle source
# File lib/twirp/error.rb, line 94
def to_s
  "<Twirp::Error code:#{code} msg:#{msg.inspect} meta:#{meta.inspect}>"
end

Private Instance Methods

validate_meta(meta) click to toggle source
# File lib/twirp/error.rb, line 105
def validate_meta(meta)
  return {} if !meta

  if !meta.is_a? Hash
    raise ArgumentError.new("Twirp::Error meta must be a Hash, but it is a #{meta.class.to_s}")
  end
  meta.each do |key, value|
    if !value.is_a?(String)
      raise ArgumentError.new("Twirp::Error meta values must be Strings, but key #{key.inspect} has the value <#{value.class.to_s}> #{value.inspect}")
    end
  end
  meta
end