Class: Onsi::ErrorResponse

Inherits:
Object
  • Object
show all
Defined in:
lib/onsi/error_responder.rb

Overview

The error response container.

Examples:

def handle_error(error)
  response = Onsi::ErrorResponse.new(400)
  response.add(400, 'bad_request', title: 'The payload was invalid')
  render_error(response)
end

Author:

  • Maddie Schipper

Since:

  • 1.0.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(status) ⇒ ErrorResponse

Create a new ErrorResponse

Parameters:

  • status (Integer)

    The HTTP status for the response.

Since:

  • 1.0.0



196
197
198
199
# File 'lib/onsi/error_responder.rb', line 196

def initialize(status)
  @status = status
  @errors = []
end

Instance Attribute Details

#statusInteger (readonly)

The HTTP status for the response.

Returns:

  • (Integer)

Since:

  • 1.0.0



190
191
192
# File 'lib/onsi/error_responder.rb', line 190

def status
  @status
end

Instance Method Details

#add(status, code, title: nil, details: nil, meta: nil) ⇒ Object

Add a renderable error to the errors

Parameters:

  • status (#to_s, nil)

    The status of the error. Usually the same as the HTTP status passed to #initialize

  • code (String)

    The error code for the error. e.g. ‘bad_request`

  • title (String, nil) (defaults to: nil)

    The user displayable title for the error.

  • details (String, nil) (defaults to: nil)

    The user displayable details for the error.

  • meta (Hash, nil) (defaults to: nil)

    Any additional metadata to associate with the error.

Since:

  • 1.0.0



215
216
217
218
219
220
221
222
223
# File 'lib/onsi/error_responder.rb', line 215

def add(status, code, title: nil, details: nil, meta: nil)
  @errors << {}.tap do |err|
    err[:status] = (status || @status).to_s
    err[:code]   = code
    err[:title]  = title      if title.present?
    err[:detail] = details    if details.present?
    err[:meta]   = Hash(meta) if meta.present?
  end
end

#as_jsonHash

Create the error objects.

Returns:

  • (Hash)

    The JSON-API error hash.

Since:

  • 1.0.0



229
230
231
# File 'lib/onsi/error_responder.rb', line 229

def as_json
  { errors: @errors.as_json }
end