Module: ConcernsOnRails::Controllers::ErrorHandleable
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/concerns_on_rails/controllers/error_handleable.rb
Overview
Installs ‘rescue_from` handlers for the three most common controller exceptions and renders them as the JSON error envelope used by Respondable.
class Api::BaseController < ApplicationController
include ConcernsOnRails::Controllers::Respondable # optional, but recommended
include ConcernsOnRails::Controllers::ErrorHandleable
end
Handled:
* ActiveRecord::RecordNotFound → 404 not_found
* ActionController::ParameterMissing → 400 parameter_missing
* ActiveRecord::RecordInvalid → 422 record_invalid (with field errors)
If Respondable is also included on the controller, the handlers delegate to ‘render_error` so the envelope shape stays in one place. Otherwise the handlers render the same envelope inline.
Each handler is a public instance method, so subclasses can override the message wording or response shape without re-declaring the ‘rescue_from`.
Instance Method Summary collapse
- #handle_parameter_missing(error) ⇒ Object
- #handle_record_invalid(error) ⇒ Object
- #handle_record_not_found(error) ⇒ Object
Instance Method Details
#handle_parameter_missing(error) ⇒ Object
41 42 43 44 45 46 47 |
# File 'lib/concerns_on_rails/controllers/error_handleable.rb', line 41 def handle_parameter_missing(error) render_error_envelope( message: "Parameter missing: #{error.param}", code: "parameter_missing", status: :bad_request ) end |
#handle_record_invalid(error) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/concerns_on_rails/controllers/error_handleable.rb', line 49 def handle_record_invalid(error) record = error.respond_to?(:record) ? error.record : nil details = record.respond_to?(:errors) ? record.errors. : nil render_error_envelope( message: error., code: "record_invalid", status: :unprocessable_entity, errors: details ) end |
#handle_record_not_found(error) ⇒ Object
33 34 35 36 37 38 39 |
# File 'lib/concerns_on_rails/controllers/error_handleable.rb', line 33 def handle_record_not_found(error) render_error_envelope( message: error., code: "not_found", status: :not_found ) end |