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.



78
79
80
81
82
# 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

Instance Attribute Details

#causeObject

used when wrapping another error, but this is not serialized



72
73
74
# File 'lib/twirp/error.rb', line 72

def cause
  @cause
end

#codeObject (readonly)

Returns the value of attribute code.



70
71
72
# File 'lib/twirp/error.rb', line 70

def code
  @code
end

#metaObject (readonly)

Returns the value of attribute meta.



70
71
72
# File 'lib/twirp/error.rb', line 70

def meta
  @meta
end

#msgObject (readonly)

Returns the value of attribute msg.



70
71
72
# File 'lib/twirp/error.rb', line 70

def msg
  @msg
end

Class Method Details

.internal_with(err) ⇒ Object

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



64
65
66
67
68
# 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

.valid_code?(code) ⇒ Boolean

Returns:

  • (Boolean)


49
50
51
# 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

Instance Method Details

#inspectObject



98
99
100
# File 'lib/twirp/error.rb', line 98

def inspect
  to_s
end

#to_hObject

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



85
86
87
88
89
90
91
92
# File 'lib/twirp/error.rb', line 85

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

#to_sObject



94
95
96
# File 'lib/twirp/error.rb', line 94

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