Created
April 9, 2013 17:26
-
-
Save kgodard/5347621 to your computer and use it in GitHub Desktop.
rails controller formatted error responses for multiple error types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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