Class: SenroUsecaser::Error

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

Overview

Represents an error in a Result

Examples:

Basic error

error = SenroUsecaser::Error.new(
  code: :invalid_email,
  message: "Email format is invalid",
  field: :email
)

Error from exception

begin
  # some code that raises
rescue => e
  error = SenroUsecaser::Error.new(
    code: :unexpected_error,
    message: e.message,
    cause: e
  )
end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(code:, message:, field: nil, cause: nil) ⇒ Error

: (code: Symbol, message: String, ?field: Symbol?, ?cause: Exception?) -> void



39
40
41
42
43
44
# File 'lib/senro_usecaser/error.rb', line 39

def initialize(code:, message:, field: nil, cause: nil)
  @code = code
  @message = message
  @field = field
  @cause = cause
end

Instance Attribute Details

#cause ⇒ Object (readonly)

: Exception?



36
37
38
# File 'lib/senro_usecaser/error.rb', line 36

def cause
  @cause
end

#code ⇒ Object (readonly)

: Symbol



27
28
29
# File 'lib/senro_usecaser/error.rb', line 27

def code
  @code
end

#field ⇒ Object (readonly)

: Symbol?



33
34
35
# File 'lib/senro_usecaser/error.rb', line 33

def field
  @field
end

#message ⇒ Object (readonly)

: String



30
31
32
# File 'lib/senro_usecaser/error.rb', line 30

def message
  @message
end

Class Method Details

.from_exception(exception, code: :exception) ⇒ Object

Creates an Error from an exception

: (Exception, ?code: Symbol) -> Error



49
50
51
52
53
54
55
# File 'lib/senro_usecaser/error.rb', line 49

def self.from_exception(exception, code: :exception)
  new(
    code: code,
    message: exception.message,
    cause: exception
  )
end

Instance Method Details

#==(other) ⇒ Object

: (Error) -> bool



65
66
67
68
69
# File 'lib/senro_usecaser/error.rb', line 65

def ==(other)
  return false unless other.is_a?(Error)

  code == other.code && message == other.message && field == other.field && cause == other.cause
end

#caused_by_exception? ⇒ Boolean

Returns true if this error was caused by an exception

: () -> bool

Returns:

  • (Boolean)


60
61
62
# File 'lib/senro_usecaser/error.rb', line 60

def caused_by_exception?
  !cause.nil?
end

#inspect ⇒ Object

: () -> String



78
79
80
81
82
83
84
85
86
# File 'lib/senro_usecaser/error.rb', line 78

def inspect
  parts = [
    "code=#{code.inspect}",
    "message=#{message.inspect}",
    "field=#{field.inspect}"
  ]
  parts << "cause=#{cause.class}" if cause
  "#<#{self.class.name} #{parts.join(" ")}>"
end

#to_s ⇒ Object

: () -> String



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

def to_s
  base = field ? "[#{field}] #{message} (#{code})" : "#{message} (#{code})"
  cause ? "#{base} caused by #{cause.class}" : base
end