由于门卫 API 中定义的类将扩展 Application 控制器,我们可以在 Application 控制器中定义以下内容
unless Rails.application.config.consider_all_requests_local
rescue_from Exception, with: :render_500
rescue_from ActionController::RoutingError, with: :render_404
rescue_from ActionController::UnknownController, with: :render_404
rescue_from ActionController::UnknownAction, with: :render_404
rescue_from ActiveRecord::RecordNotFound, with: :render_404
end
private
#error handling
def render_404(exception)
@not_found_path = exception.message
respond_to do |format|
format.html { render file: 'public/404.html', status: 404, layout: false }
format.all { render nothing: true, status: 404 }
end
end
def render_500(exception)
@error = exception
respond_to do |format|
format.html { render file: 'public/500.html', status: 500, layout: false }
format.all { render nothing: true, status: 500}
end
end
然后你可以在ErrorsController中专门定义错误
class ErrorsController < ActionController::Base
def not_found
if request.url.match('api')
render :json => {:error => "Not Found"}.to_json, :status => 404
else
render file: 'public/404.html', :status => 404, layout: false
end
end
def exception
if request.url.match('api')
render :json => {:error => "Internal Server Error"}.to_json, :status => 500
else
render file: 'public/500.html', :status => 500, layout: false
end
end
end
希望这会有所帮助。