Module: Core::Helpers::Errors

Included in:
Controllers::Base
Defined in:
lib/core/helpers/errors.rb,
lib/core/helpers/errors/base.rb,
lib/core/helpers/errors/forbidden.rb,
lib/core/helpers/errors/not_found.rb,
lib/core/helpers/errors/bad_request.rb

Overview

This module defines method to raise HTTP errors in the routes easily.

Author:

Defined Under Namespace

Classes: BadRequest, Base, Forbidden, NotFound

Instance Method Summary collapse

Instance Method Details

#api_bad_request(field, message: 'required') ⇒ Object

Stops the execution to return a BAD REQUEST response.

Parameters:

  • field (String)

    the field in params concerned by the error.

  • message (String) (defaults to: 'required')

    the message if different of “required”.



36
37
38
# File 'lib/core/helpers/errors.rb', line 36

def api_bad_request(field, message: 'required')
  api_error 400, "#{field}.#{message}"
end

#api_error(status, message) ⇒ Object

Stops the executing and raises an HTTP error in the route. The message MUST be of the for <field>.<error> to be correctly parsed. The action is automatically parsed from the route call and added.

Parameters:

  • status (Integer)

    the HTTP status code the response will have

  • message (String)

    the raw message to split and format as body.



19
20
21
22
23
24
# File 'lib/core/helpers/errors.rb', line 19

def api_error(status, message)
  field, error = message.split('.')
  docs = settings.errors.try(field).try(error)
  errors = { status: status, field: field, error: error, docs: docs }
  halt status, errors.to_json
end

#api_forbidden(field, message: 'forbidden') ⇒ Object

Stops the execution to return a FORBIDDEN response.

Parameters:

  • field (String)

    the field in params concerned by the error.

  • message (String) (defaults to: 'forbidden')

    the message if different of “forbidden”.



43
44
45
# File 'lib/core/helpers/errors.rb', line 43

def api_forbidden(field, message: 'forbidden')
  api_error 403, "#{field}.#{message}"
end

#api_not_found(field, message: 'unknown') ⇒ Object

Stops the execution to return a NOT FOUND response.

Parameters:

  • field (String)

    the field in params concerned by the error.

  • message (String) (defaults to: 'unknown')

    the message if different of “unknown”.



29
30
31
# File 'lib/core/helpers/errors.rb', line 29

def api_not_found(field, message: 'unknown')
  api_error 404, "#{field}.#{message}"
end