Class: Utopia::ExceptionHandler

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

Instance Method Summary collapse

Constructor Details

#initialize(app, location) ⇒ ExceptionHandler

Returns a new instance of ExceptionHandler.



27
28
29
30
31
32
33
# File 'lib/utopia/exception_handler.rb', line 27

def initialize(app, location)
	@app = app
	
	@location = location
	
	self.freeze
end

Instance Method Details

#call(env) ⇒ Object



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/utopia/exception_handler.rb', line 62

def call(env)
	begin
		return @app.call(env)
	rescue Exception => exception
		# An error has occurred, log it:
		log = ::Logger.new(env['rack.errors'] || $stderr)
		
		log.error "Exception #{exception.to_s.dump}!"
		
		exception.backtrace.each do |line|
			log.error line
		end
		
		# If the error occurred while accessing the error handler, we finish with a fatal error:
		if env[Rack::PATH_INFO] == @location
			return fatal_error(env, exception)
		else
			# If redirection fails, we also finish with a fatal error:
			begin
				return redirect(env, exception)
			rescue
				return fatal_error(env, exception)
			end
		end
	end
end

#fatal_error(env, exception) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/utopia/exception_handler.rb', line 41

def fatal_error(env, exception)
	body = StringIO.new

	body.puts "<!DOCTYPE html><html><head><title>Fatal Error</title></head><body>"
	body.puts "<h1>Fatal Error</h1>"
	body.puts "<p>While requesting resource #{Trenni::Strings::to_html env[Rack::PATH_INFO]}, a fatal error occurred.</p>"
	body.puts "<blockquote><strong>#{Trenni::Strings::to_html exception.class.name}</strong>: #{Trenni::Strings::to_html exception.to_s}</blockquote>"
	body.puts "<p>There is nothing more we can do to fix the problem at this point.</p>"
	body.puts "<p>We apologize for the inconvenience.</p>"
	body.puts "</body></html>"
	body.rewind

	return [400, {HTTP::CONTENT_TYPE => "text/html"}, body]
end

#freezeObject



35
36
37
38
39
# File 'lib/utopia/exception_handler.rb', line 35

def freeze
	@location.freeze
	
	super
end

#redirect(env, exception) ⇒ Object



56
57
58
59
60
# File 'lib/utopia/exception_handler.rb', line 56

def redirect(env, exception)
	response = @app.call(env.merge(Rack::PATH_INFO => @location, Rack::REQUEST_METHOD => Rack::GET))
	
	return [500, response[1], response[2]]
end