Module: HumanError::RescuableResource::ClassMethods

Defined in:
lib/human_error/rescuable_resource.rb

Instance Method Summary collapse

Instance Method Details

#rescue_resource(_resource_name, from:, via:) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/MethodLength, Style/GuardClause



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/human_error/rescuable_resource.rb', line 9

def rescue_resource(_resource_name, from:, via:)
  lookup_library = via

  if from.include? 'persistence'
    rescue_from HumanError::Errors::ResourcePersistenceError do |e|
      error = lookup_library.fetch(
              'ResourcePersistenceError',
              resource_name: e.resource_name,
              attributes:    e.attributes,
              errors:        e.errors,
              action:        action_name)

      render json:   error,
             status: error.http_status
    end
  end

  if from.include? 'not_found'
    rescue_from HumanError::Errors::ResourceNotFoundError do |e|
      resource_id = e.resource_id.is_a?(Array) ? e.resource_id : [e.resource_id]

      error = lookup_library.fetch(
              'ResourceNotFoundError',
              resource_name: e.resource_name,
              resource_id:   resource_id,
              action:        action_name)

      render json:   error,
             status: error.http_status
    end
  end

  if from.include? 'association'
    rescue_from HumanError::Errors::AssociationError do |e|
      error = lookup_library.fetch(
              'AssociationError',
              resource_name:    e.resource_name,
              association_name: e.association_name,
              association_id:   e.association_id,
              attributes:       e.attributes)

      render json:   error,
             status: error.http_status
    end
  end
end