Class: ApiHammer::ShowTextExceptions

Inherits:
Object
  • Object
show all
Defined in:
lib/api_hammer/show_text_exceptions.rb

Overview

Rack middleware to rescue any exceptions and return an appropriate message for the current environment, with a nice concise bit of text for errors.

ideally this should be placed as close to the application itself as possible (last middleware used) so that the exception will not bubble past other middleware, skipping it.

like Sinatra::ShowExceptions or Rack::ShowExceptions, but not a huge blob of html. (note: those middlewares have a #prefers_plain_text? method which makes them behave like this, but it's simpler and more reliable to roll our own than monkey-patch those)

Defined Under Namespace

Modules: AllExceptionsExceptOnesWeMustNotRescue

Instance Method Summary collapse

Constructor Details

#initialize(app, options) ⇒ ShowTextExceptions

Returns a new instance of ShowTextExceptions.



25
26
27
28
# File 'lib/api_hammer/show_text_exceptions.rb', line 25

def initialize(app, options)
  @app=app
  @options = options
end

Instance Method Details

#call(env) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/api_hammer/show_text_exceptions.rb', line 29

def call(env)
  begin
    @app.call(env)
  rescue AllExceptionsExceptOnesWeMustNotRescue => e
    full_error_message = (["#{e.class}: #{e.message}"] + e.backtrace.map{|l| "  #{l}" }).join("\n")
    if @options[:logger]
      @options[:logger].error(full_error_message)
    end
    if @options[:full_error]
      body = full_error_message
    else
      body = "Internal Server Error\n"
    end
    [500, {'Content-Type' => 'text/plain'}, [body]]
  end
end