Class: Hmibo::Error

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

Overview

Error class for structured error handling

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Error.



8
9
10
11
12
13
# File 'lib/hmibo/error.rb', line 8

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

Instance Attribute Details

#codeObject (readonly)

Returns the value of attribute code.



6
7
8
# File 'lib/hmibo/error.rb', line 6

def code
  @code
end

#fieldObject (readonly)

Returns the value of attribute field.



6
7
8
# File 'lib/hmibo/error.rb', line 6

def field
  @field
end

#idObject (readonly)

Returns the value of attribute id.



6
7
8
# File 'lib/hmibo/error.rb', line 6

def id
  @id
end

#messageObject (readonly)

Returns the value of attribute message.



6
7
8
# File 'lib/hmibo/error.rb', line 6

def message
  @message
end

Class Method Details

.forbidden(message = 'Forbidden') ⇒ Object



55
56
57
# File 'lib/hmibo/error.rb', line 55

def self.forbidden(message = 'Forbidden')
  new(message, code: 403)
end

.from_active_record(record, id: nil) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/hmibo/error.rb', line 28

def self.from_active_record(record, id: nil)
  errors = []

  record.errors.each do |error|
    errors << new(
      error.full_message,
      code: 422,
      id: id,
      field: error.attribute
    )
  end

  errors
end

.not_found(message = 'Record not found') ⇒ Object



47
48
49
# File 'lib/hmibo/error.rb', line 47

def self.not_found(message = 'Record not found')
  new(message, code: 404)
end

.server_error(message = 'Internal server error') ⇒ Object



59
60
61
# File 'lib/hmibo/error.rb', line 59

def self.server_error(message = 'Internal server error')
  new(message, code: 500)
end

.unauthorized(message = 'Unauthorized') ⇒ Object



51
52
53
# File 'lib/hmibo/error.rb', line 51

def self.unauthorized(message = 'Unauthorized')
  new(message, code: 401)
end

.validation_error(message, field: nil) ⇒ Object



43
44
45
# File 'lib/hmibo/error.rb', line 43

def self.validation_error(message, field: nil)
  new(message, code: 422, field: field)
end

Instance Method Details

#to_hObject



15
16
17
18
19
20
21
22
# File 'lib/hmibo/error.rb', line 15

def to_h
  {
    message: @message,
    code: @code,
    id: @id,
    field: @field
  }.compact
end

#to_json(*args) ⇒ Object



24
25
26
# File 'lib/hmibo/error.rb', line 24

def to_json(*args)
  to_h.to_json(*args)
end