Module: Goliath::Rack::Validator

Class Method Summary collapse

Class Method Details

.safely(env, headers = {}) ⇒ Object

Execute a block of code safely.

If the block raises any exception that derives from Goliath::Validation::Error (see specifically those in goliath/validation/standard_http_errors.rb), it will be turned into the corresponding 4xx response with a corresponding message.

If the block raises any other kind of error, we log it and return a less-communicative 500 response.

Examples:

# will convert the ForbiddenError exception into a 403 response
# and an uncaught error in do_something_risky! into a 500 response
safely(env, headers) do
  raise ForbiddenError unless ['valid'] == true
  do_something_risky!
  [status, headers, body]
end

Parameters:

  • env (Goliath::Env)

    The current request env

  • headers (Hash) (defaults to: {})

    Response headers to preserve in an error response



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/goliath/rack/validator.rb', line 38

def safely(env, headers={})
  begin
    yield
  rescue Goliath::Validation::Error => e
    validation_error(e.status_code, e.message, e.headers.merge(headers))
  rescue Exception => e
    env.logger.error(e.message)
    env.logger.error(e.backtrace.join("\n"))
    validation_error(500, e.message, headers)
  end
end

.validation_error(status_code, msg, headers = {}) ⇒ Object

Parameters:

  • status_code (Integer)

    HTTP status code for this error.

  • msg (String)

    message to inject into the response body.

  • headers (Hash) (defaults to: {})

    Response headers to preserve in an error response; (the Content-Length header, if any, is removed)



10
11
12
13
# File 'lib/goliath/rack/validator.rb', line 10

def validation_error(status_code, msg, headers={})
  headers.delete('Content-Length')
  [status_code, headers, {:error => msg}]
end