Class: Utopia::Exceptions::Handler

Inherits:
Object
  • Object
show all
Defined in:
lib/utopia/exceptions/handler.rb

Overview

A middleware which catches exceptions and performs an internal redirect.

Instance Method Summary collapse

Constructor Details

#initialize(app, location = "/errors/exception") ⇒ Handler

Returns a new instance of Handler.

Parameters:

  • location (String) (defaults to: "/errors/exception")

    Peform an internal redirect to this location when an exception is raised.



14
15
16
17
18
# File 'lib/utopia/exceptions/handler.rb', line 14

def initialize(app, location = "/errors/exception")
  @app = app
  
  @location = location
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/utopia/exceptions/handler.rb', line 28

def call(env)
  begin
    return @app.call(env)
  rescue Exception => exception
    Console.warn(self, "An error occurred while processing the request.", error: exception)
    
    begin
      # We do an internal redirection to the error location:
      error_request = env.merge(
        Rack::PATH_INFO => @location,
        Rack::REQUEST_METHOD => Rack::GET,
        "utopia.exception" => exception,
      )
      
      error_response = @app.call(error_request)
      error_response[0] = 500
      
      return error_response
    rescue Exception => exception
      # If redirection fails, we also finish with a fatal error:
      Console.error(self, "An error occurred while invoking the error handler.", error: exception)
      return [500, {"content-type" => "text/plain"}, ["An error occurred while processing the request."]]
    end
  end
end

#freezeObject



20
21
22
23
24
25
26
# File 'lib/utopia/exceptions/handler.rb', line 20

def freeze
  return self if frozen?
  
  @location.freeze
  
  super
end