복붙노트

[RUBY-ON-RAILS] A는 컨트롤러를 레일에 모든 예외를 잡아라

RUBY-ON-RAILS

A는 컨트롤러를 레일에 모든 예외를 잡아라

이 같은 레일 컨트롤러의 모든 uncatched 예외를 잡을 수있는 방법이 있나요 :

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

감사합니다

해결법

  1. ==============================

    1.

    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
    
  2. ==============================

    2.또한 rescue_from 방법을 정의 할 수 있습니다.

    또한 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_handler 보석 같은 것을 사용합니다. 보너스로,이 방법은 또한 응용 프로그램이 표시되지 않는 것을 요청 구문 분석 또는 데이터베이스 연결 오류와 같은 미들웨어 계층에서 발생하는 예외를 처리합니다. exception_notifier 보석도 관심이있을 수 있습니다.

  3. ==============================

    3.당신은 유형별로 예외를 잡을 수 있습니다 :

    당신은 유형별로 예외를 잡을 수 있습니다 :

    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
    
  4. ==============================

    4.인수와 구조는 오류를 구출합니다.

    인수와 구조는 오류를 구출합니다.

    그래서, 당신은 할 수 있습니다 :

    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
    
  5. ==============================

    5.당신이 정말로 캐치 모든 것을 원하는 경우 사실, 당신은 당신이 보통 PublicExceptions에 의해 처리되는 동작을 사용자 정의하자 자신의 예외 응용 프로그램을 작성, 미들웨어 : https://github.com/rails/rails/blob/4-2 -stable / actionpack / lib 디렉토리 / action_dispatch / 미들웨어 / public_exceptions.rb

    당신이 정말로 캐치 모든 것을 원하는 경우 사실, 당신은 당신이 보통 PublicExceptions에 의해 처리되는 동작을 사용자 정의하자 자신의 예외 응용 프로그램을 작성, 미들웨어 : https://github.com/rails/rails/blob/4-2 -stable / actionpack / lib 디렉토리 / action_dispatch / 미들웨어 / public_exceptions.rb

    다른 답변의 무리는 당신을 위해 이렇게 보석을 공유하지만 당신이 그냥보고 스스로 할 수없는 이유가 정말 없습니다.

    주의 : 메이크업 확실히 당신은 당신의 예외 핸들러에서 예외가 발생하지 않습니다. 그렇지 않으면 당신은 못생긴 FAILSAFE_RESPONSE https://github.com/rails/rails/blob/4-2-stable/actionpack/lib/action_dispatch/middleware/show_exceptions.rb#L4-L22를 얻을 수

    BTW, 컨트롤러의 동작이 rescuable에서 온다 : https://github.com/rails/rails/blob/4-2-stable/activesupport/lib/active_support/rescuable.rb#L32-L51

  6. from https://stackoverflow.com/questions/3694153/catch-all-exceptions-in-a-rails-controller by cc-by-sa and MIT license