class Hanami::Middleware::RenderErrors

Rack middleware that rescues errors raised by the app renders friendly error responses, via a given “errors app”.

By default, this is enabled only in production mode.

@see Hanami::Config#render_errors @see Hanani::Middleware::PublicErrorsApp

@api private @since 2.1.0

Public Class Methods

new(app, config, errors_app) click to toggle source

@api private @since 2.1.0

# File lib/hanami/middleware/render_errors.rb, line 48
def initialize(app, config, errors_app)
  @app = app
  @config = config
  @errors_app = errors_app
end

Public Instance Methods

call(env) click to toggle source

@api private @since 2.1.0

# File lib/hanami/middleware/render_errors.rb, line 56
def call(env)
  @app.call(env)
rescue Exception => exception
  raise unless @config.render_errors

  render_exception(env, exception)
end

Private Instance Methods

render_exception(env, exception) click to toggle source
# File lib/hanami/middleware/render_errors.rb, line 66
def render_exception(env, exception)
  request = Rack::Request.new(env)
  renderable = RenderableException.new(exception, responses: @config.render_error_responses)

  status = renderable.status_code
  request.path_info = "/#{status}"
  request.set_header(Rack::REQUEST_METHOD, "GET")

  @errors_app.call(request.env)
rescue Exception => failsafe_error
  # rubocop:disable Style/StderrPuts
  $stderr.puts "Error during exception rendering: #{failsafe_error}\n  #{failsafe_error.backtrace * "\n  "}"
  # rubocop:enable Style/StderrPuts

  [
    500,
    {"Content-Type" => "text/plain; charset=utf-8"},
    ["Internal Server Error"]
  ]
end