Class: Useless::Rack::Middleware::Exceptions

Inherits:
Object
  • Object
show all
Defined in:
lib/useless/rack/middleware/exceptions.rb

Overview

‘Exceptions` is a Rack middleware that handles any exceptions raised by it’s app. It has two responsibilities:

1. log the exception trace, if a logger is available, and
2. return a 500 response with the appropriate message

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Exceptions

Returns a new instance of Exceptions.



9
10
11
# File 'lib/useless/rack/middleware/exceptions.rb', line 9

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/useless/rack/middleware/exceptions.rb', line 13

def call(env)
  @app.call(env)
rescue => exception
  # First, format the exception trace
  trace = exception.message + "\n" + exception.backtrace.join("\n")

  # If a logger is available,
  if env['useless.logger']
    # log the trace as fatal.
    env['useless.logger'].fatal trace
  end

  # Next, if the request is authenticated by an admin or we are in development or test,
  if (env['useless.user'] and env['useless.user']['admin']) or
      ENV['RACK_ENV'] == 'development'
    # we will return the trace;
    message = trace
  else
    # otherwise, return a generic message.
    message = 'An internal server error occurred. Please try again later.'
  end

  # Finally, return the 500 error.
  [500, {'Content-Type' => 'text/plain'}, [message]]
end