Module: Goliath::Rack::Validator

Defined in:
lib/grass/goliath/rack/validator.rb

Constant Summary collapse

ERROR =
'error'

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



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

def safely(env, headers={})
  begin
    yield
  rescue Goliath::Validation::Error => e
    validation_error(e.status_code, e.message, 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)



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

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