Class: Utopia::Exceptions::Handler

Inherits:
Protocol::HTTP::Middleware
  • 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.



18
19
20
21
22
# File 'lib/utopia/exceptions/handler.rb', line 18

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

Instance Method Details

#call(request) ⇒ Object

Convert application exceptions into internal-server-error responses.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/utopia/exceptions/handler.rb', line 37

def call(request)
	begin
		return @delegate.call(request)
	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 = request.with(
				method: "GET",
				path: @location
			)
			error_request.exception = exception
			
			error_response = Response.wrap(@delegate.call(error_request))
			error_response.status = 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 Response[500, {"content-type" => "text/plain"}, ["An error occurred while processing the request."]]
		end
	end
end

#freezeObject

Freeze this object and its internal state.



26
27
28
29
30
31
32
# File 'lib/utopia/exceptions/handler.rb', line 26

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