Skip to content

Instantly share code, notes, and snippets.

@kgodard
Created April 9, 2013 17:26
Show Gist options
  • Save kgodard/5347621 to your computer and use it in GitHub Desktop.
Save kgodard/5347621 to your computer and use it in GitHub Desktop.
rails controller formatted error responses for multiple error types
module Api
class ApiApplicationController < ActionController::Base
protect_from_forgery
before_filter :authenticate_api_user!
rescue_from Exception, :with => :render_500
rescue_from ActiveRecord::RecordNotFound, :with => :render_404
rescue_from ActionController::RoutingError, :with => :render_404
rescue_from ActionController::UnknownController, :with => :render_404
rescue_from ActionController::UnknownAction, :with => :render_404
private
def render_404(exception)
logger.error(exception)
respond_to do |format|
format.html { render :template => "/errors/404.html.erb", :status => 404 }
format.any do
method = "to_#{request_format}"
text = {}.respond_to?(method) ? {:error => 'not found'}.send(method) : ""
render :text => text, :status => 404
end
end
end
def render_500(exception)
logger.error(exception)
respond_to do |format|
format.html { render :template => "/errors/500.html.erb", :status => 500 }
format.any do
method = "to_#{request_format}"
text = {}.respond_to?(method) ? {:error => 'server error'}.send(method) : ""
render :text => text, :status => 500
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment