program tip

Rails에서 다른 Rails 예외처럼 작동하도록 어떻게 예외를 발생 시키나요?

radiobox 2020. 9. 7. 08:00
반응형

Rails에서 다른 Rails 예외처럼 작동하도록 어떻게 예외를 발생 시키나요?


일반 Rails 예외와 동일한 작업을 수행하도록 예외를 발생시키고 싶습니다. 특히 개발 모드에서는 예외 및 스택 추적을 표시하고 프로덕션 모드에서는 "죄송합니다. 문제가 발생했습니다."페이지를 표시합니다.

다음을 시도했습니다.

raise "safety_care group missing!" if group.nil?

그러나 단순히 "ERROR signing up, group missing!"development.log 파일에 기록 합니다.


특별한 조치를 취할 필요는 없습니다.

이 컨트롤러가있는 새로운 레일 앱이있는 경우 :

class FooController < ApplicationController
  def index
    raise "error"
  end
end

그리고 이동 http://127.0.0.1:3000/foo/

스택 추적에서 예외가 표시됩니다.

Rails (2.3 이후) 는 프레임 워크 자체에서 가져온 스택 추적에서 행을 필터링 하기 때문에 콘솔 로그에 전체 스택 추적이 표시되지 않을 수 있습니다 .

참조 config/initializers/backtrace_silencers.rb레일스 프로젝트에


다음과 같이 할 수 있습니다.

class UsersController < ApplicationController
  ## Exception Handling
  class NotActivated < StandardError
  end

  rescue_from NotActivated, :with => :not_activated

  def not_activated(exception)
    flash[:notice] = "This user is not activated."
    Event.new_event "Exception: #{exception.message}", current_user, request.remote_ip
    redirect_to "/"
  end

  def show
      // Do something that fails..
      raise NotActivated unless @user.is_activated?
  end
end

What you're doing here is creating a class "NotActivated" that will serve as Exception. Using raise, you can throw "NotActivated" as an Exception. rescue_from is the way of catching an Exception with a specified method (not_activated in this case). Quite a long example, but it should show you how it works.

Best wishes,
Fabian


If you need an easier way to do it, and don't want much fuss, a simple execution could be:

raise Exception.new('something bad happened!')

This will raise an exception, say e with e.message = something bad happened!

and then you can rescue it as you are rescuing all other exceptions in general.

참고URL : https://stackoverflow.com/questions/1918373/how-do-i-raise-an-exception-in-rails-so-it-behaves-like-other-rails-exceptions

반응형