捕获轨道控制器中的所有exception

有没有办法在轨道控制器中捕获所有未捕获的exception,如下所示:

def delete schedule_id = params[:scheduleId] begin Schedules.delete(schedule_id) rescue ActiveRecord::RecordNotFound render :json => "record not found" rescue ActiveRecord::CatchAll #Only comes in here if nothing else catches the error end render :json => "ok" end 

谢谢

 begin # do something dodgy rescue ActiveRecord::RecordNotFound # handle not found error rescue ActiveRecord::ActiveRecordError # handle other ActiveRecord errors rescue # StandardError # handle most other errors rescue Exception # handle everything else raise end 

你也可以定义一个rescue_from方法。

 class ApplicationController < ActionController::Base rescue_from ActionController::RoutingError, :with => :error_render_method def error_render_method respond_to do |type| type.xml { render :template => "errors/error_404", :status => 404 } type.all { render :nothing => true, :status => 404 } end true end end 

根据你的目标是什么,你可能也想考虑不在每个控制器的基础上处理exception。 相反,使用像exception_handler gem来持续地pipe理对exception的响应。 作为奖励,这种方法还将处理在中间件层发生的exception,例如请求parsing或数据库连接错误,您的应用程序看不到。 exception_notifier gem也可能是有趣的。

您可以按types捕获exception:

 rescue_from ::ActiveRecord::RecordNotFound, with: :record_not_found rescue_from ::NameError, with: :error_occurred rescue_from ::ActionController::RoutingError, with: :error_occurred # Don't resuce from Exception as it will resuce from everything as mentioned here "http://stackoverflow.com/questions/10048173/why-is-it-bad-style-to-rescue-exception-e-in-ruby" Thanks for @Thibaut Barrère for mention that # rescue_from ::Exception, with: :error_occurred protected def record_not_found(exception) render json: {error: exception.message}.to_json, status: 404 return end def error_occurred(exception) render json: {error: exception.message}.to_json, status: 500 return end 

没有参数的救援将拯救任何错误。

所以,你会想要:

 def delete schedule_id = params[:scheduleId] begin Schedules.delete(schedule_id) rescue ActiveRecord::RecordNotFound render :json => "record not found" rescue #Only comes in here if nothing else catches the error end render :json => "ok" end 

实际上,如果你真的想抓住所有的东西 ,你只需要创build你自己的exception应用程序,让你自定义通常由PublicExceptions中间件处理的行为: https : //github.com/rails/rails/blob/4-2 -stable / ActionPack的/ LIB / action_dispatch /中间件/ public_exceptions.rb

其他一些答案分享gem,这样做给你,但真的没有理由,你不能只看着他们自己做。

一个警告:确保你永远不会在exception处理程序中引发exception。 否则你得到一个丑陋的FAILSAFE_RESPONSE https://github.com/rails/rails/blob/4-2-stable/actionpack/lib/action_dispatch/middleware/show_exceptions.rb#L4-L22

顺便说一句,在控制器中的行为来自可挽救: https : //github.com/rails/rails/blob/4-2-stable/activesupport/lib/active_support/rescuable.rb#L32-L51