Catch all exceptions in a rails controller

后端 未结 6 1063
春和景丽
春和景丽 2020-11-28 02:20

Is there a way to catch all uncatched exceptions in a rails controller, like this:

def delete
  schedule_id = params[:scheduleId]
  begin
    Schedules.delet         


        
6条回答
  •  执笔经年
    2020-11-28 03:03

    You can catch exceptions by type:

    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
    

提交回复
热议问题