Class: Twirp::Error

Inherits:
Object
  • Object
show all
Defined in:
lib/twirp/error.rb

Overview

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.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(code, msg, meta = nil) ⇒ Error

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.



64
65
66
67
68
# File 'lib/twirp/error.rb', line 64

def initialize(code, msg, meta=nil)
  @code = code.to_sym
  @msg = msg.to_s
  @meta = validate_meta(meta)
end

Instance Attribute Details

#causeObject

used when wrapping another error, but this is not serialized



58
59
60
# File 'lib/twirp/error.rb', line 58

def cause
  @cause
end

#codeObject (readonly)

Returns the value of attribute code.



56
57
58
# File 'lib/twirp/error.rb', line 56

def code
  @code
end

#metaObject (readonly)

Returns the value of attribute meta.



56
57
58
# File 'lib/twirp/error.rb', line 56

def meta
  @meta
end

#msgObject (readonly)

Returns the value of attribute msg.



56
57
58
# File 'lib/twirp/error.rb', line 56

def msg
  @msg
end

Class Method Details

.internal_with(err) ⇒ Object

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



50
51
52
53
54
# File 'lib/twirp/error.rb', line 50

def self.internal_with(err)
  twerr = internal err.message, cause: err.class.name
  twerr.cause = err
  twerr
end

.valid_code?(code) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
# File 'lib/twirp/error.rb', line 35

def self.valid_code?(code)
  ERROR_CODES_TO_HTTP_STATUS.key? code # one of the valid symbols
end

Instance Method Details

#inspectObject



83
84
85
# File 'lib/twirp/error.rb', line 83

def inspect
  to_s
end

#to_hObject



70
71
72
73
74
75
76
77
# File 'lib/twirp/error.rb', line 70

def to_h
  h = {
    code: @code,
    msg: @msg,
  }
  h[:meta] = @meta unless @meta.empty?
  h
end

#to_sObject



79
80
81
# File 'lib/twirp/error.rb', line 79

def to_s
  "<Twirp::Error code:#{code} msg:#{msg.inspect} meta:#{meta.inspect}>"
end