UtopiaSourceUtopiaExceptionsHandler

class Handler

A middleware which catches exceptions and performs an internal redirect.

Definitions

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

Implementation

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

def freeze

Freeze this object and its internal state.

Signature

returns self

This object.

Implementation

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

def call(env)

Convert application exceptions into internal-server-error responses.

Signature

parameter env Hash

The Rack environment.

returns Array

The application or generated error response.

Implementation

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