Skip to content

Instantly share code, notes, and snippets.

@jhubert
Last active December 26, 2015 09:49
Show Gist options
  • Save jhubert/7132739 to your computer and use it in GitHub Desktop.
Save jhubert/7132739 to your computer and use it in GitHub Desktop.
This is an abstraction of the error handling that I'm using on an API that I'm working on.
module Api
module V1
class BaseController < ActionController::Base
class ::BMP::CompanyNotFound < ActiveRecord::RecordNotFound; end
class ::BMP::Unauthenticated < StandardError; end
doorkeeper_for :all
respond_to :json
rescue_from Exception, :with => :handle_exceptions
def noop
raise ActionController::RoutingError.new(params[:path])
end
def doorkeeper_unauthorized_render_options
raise BMP::Unauthenticated
end
private
def render_error(message, status)
# Supress error codes in case
if params[:suppress_response_codes] == "true"
render :template => 'api/v1/base/error', :status => :ok, :locals => { :message => message, :response_code => Rack::Utils.status_code(status) }
else
render :template => 'api/v1/base/error', :status => status, :locals => { :message => message }
end
end
# Handle exceptions
def handle_exceptions(e)
case e
# Handling unauthorized attempts
when BMP::Unauthenticated
render_error 'You must be authenticated to use this API', :unauthorized
# Handling exception when company not found
when BMP::CompanyNotFound
render_error 'Company Not Found', :not_found
# Handling exception when record not found
when ActiveRecord::RecordNotFound
render_error 'Object Not Found', :not_found
# Handling exception when there was no route that matched
when ActionController::RoutingError
render_error 'Endpoint Does Not Exist', :not_found
else
internal_error(e)
end
end
def internal_error(exception)
notify_airbrake(exception)
if Rails.application.config.consider_all_requests_local
raise
else
# Render a pretty page for production with an error message
render_error 'A server error occured. The developers have been notified.', :internal_server_error
end
end
end
end
end
object false
node(:message) { @message }
node(:error_code, :unless => @error_code.blank?) { @error_code }
node(:more_info, :unless => @more_info.blank?) { @more_info }
node(:response_code, :unless => @response_code.blank?) { @response_code }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment