Skip to content

Instantly share code, notes, and snippets.

@magnum
Last active December 17, 2015 21:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save magnum/5676381 to your computer and use it in GitHub Desktop.
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
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
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