Last active
December 17, 2015 21:39
-
-
Save magnum/5676381 to your computer and use it in GitHub Desktop.
custom error handling in rails, allows to respond with json when exeptions are thrown in api controllers and with standard error handling in all other cases
This file contains 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
class ApplicationController < ActionController::Base | |
protect_from_forgery | |
# CUSTOM EXCEPTION HANDLING | |
rescue_from Exception do |e| | |
error(e) | |
end | |
def routing_error | |
raise ActionController::RoutingError.new(params[:path]) | |
end | |
protected | |
def error(e) | |
#render :template => "#{Rails::root}/public/404.html" | |
if env["ORIGINAL_FULLPATH"] =~ /^\/api/ | |
error_info = { | |
:error => "internal-server-error", | |
:exception => "#{e.class.name} : #{e.message}", | |
} | |
error_info[:trace] = e.backtrace[0,10] if Rails.env.development? | |
render :json => error_info.to_json, :status => 500 | |
else | |
#render :text => "500 Internal Server Error", :status => 500 # You can render your own template here | |
raise e | |
end | |
end | |
# ... | |
end |
This file contains 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
MyApp::Application.routes.draw do | |
# ... | |
# Any other routes are handled here (as ActionDispatch prevents RoutingError from hitting ApplicationController::rescue_action). | |
match "*path", :to => "application#routing_error", :via => :all | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment