Class: Gritz::Middleware::ExceptionMapper

Inherits:
Object
  • Object
show all
Defined in:
/home/runner/work/gritz/gritz/sources/gritz-core/lib/gritz/middleware/exception_mapper.rb

Overview

Converts application exceptions to safe RPC errors.

Instance Method Summary collapse

Constructor Details

#initialize(app, mappings: {}, expose_errors: false, passthrough_remote_errors: false) ⇒ ExceptionMapper

Returns a new instance of ExceptionMapper.



10
11
12
13
14
15
# File '/home/runner/work/gritz/gritz/sources/gritz-core/lib/gritz/middleware/exception_mapper.rb', line 10

def initialize(app, mappings: {}, expose_errors: false, passthrough_remote_errors: false)
  @app = app
  @mappings = mappings
  @expose_errors = expose_errors
  @passthrough_remote_errors = passthrough_remote_errors
end

Instance Method Details

#call(context) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File '/home/runner/work/gritz/gritz/sources/gritz-core/lib/gritz/middleware/exception_mapper.rb', line 17

def call(context)
  @app.call(context)
rescue Gritz::Error => e
  raise unless e.remote? && !@passthrough_remote_errors

  raise_internal(context, e)
rescue StandardError => e
  mapping = @mappings.find { |klass, _| e.is_a?(klass) }&.last
  if mapping
    raise(mapping.respond_to?(:call) ? mapping.call(e) : Errors.for_code(mapping).new(e.message))
  end

  case e.class.name
  when "Async::GRPC::DeadlineExceededError"
    raise Errors::DeadlineExceeded, "deadline exceeded"
  when "ActiveRecord::RecordNotFound"
    raise Errors::NotFound, "record not found"
  when "ActiveRecord::RecordInvalid"
    raise Errors::InvalidArgument, "invalid record"
  end

  raise_internal(context, e)
end