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
# File 'lib/utopia/exception_handler.rb', line 27

def initialize(app, location)
  @app = app

  @location = location
end

Instance Method Details

#call(env) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/utopia/exception_handler.rb', line 54

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['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



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/utopia/exception_handler.rb', line 33

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['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, {"Content-Type" => "text/html"}, body]
end

#redirect(env, exception) ⇒ Object



48
49
50
51
52
# File 'lib/utopia/exception_handler.rb', line 48

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