Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Render API Errors in Rails
class APIController < ApplicationController
include JSONErrors
# ...
end
# app/controllers/concerns/json_errors.rb
module JSONErrors
extend ActiveSupport::Concern
included do
rescue_from StandardError, with: :render_500
rescue_from ActiveRecord::RecordNotFound, with: :render_404 # Mongoid::Errors::DocumentNotFound
rescue_from ActionController::ParameterMissing, with: :render_400
def render_400(errors = 'required parameters invalid')
render_errors(errors, 400)
end
def render_401(errors = 'unauthorized access')
render_errors(errors, 401)
end
def render_404(errors = 'not found')
render_errors(errors, 404)
end
def render_422(errors = 'could not save data')
render_errors(errors, 422)
end
def render_500(errors = 'internal server error')
render_errors(errors, 500)
end
def render_errors(errors, status = 400)
data = {
status: 'failed',
errors: Array.wrap(errors)
}
render json: data , status: status
end
def render_object_errors(obj, status = 400)
if obj.is_a?(ActiveRecord::Base) # ActiveModel::Model for Mongoid
render_object_errors(obj.errors, status)
elsif obj.is_a?(ActiveModel::Errors)
render_errors(obj.full_messages, status)
else
render_errors(obj, status)
end
end
end
end
@flyfy1

This comment has been minimized.

Copy link

@flyfy1 flyfy1 commented Sep 26, 2020

thanks, that's really thoughful.

One thing to note: JSONErrors should better be renamed as JsonErrors so that auto_includable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment