如何在Rails中引发异常,使其行为与其他Rails异常一样?

Chi*_*tel 89 exception-handling ruby-on-rails exception

我想提出一个异常,以便它正常的Rails异常做同样的事情.特别是,在开发模式下显示异常和堆栈跟踪,并在生产模式下显示"我们很抱歉,但出现了问题"页面.

我尝试了以下方法:

raise "safety_care group missing!" if group.nil?
Run Code Online (Sandbox Code Playgroud)

但它只是写入"ERROR signing up, group missing!"development.log文件

lev*_*lex 133

你不需要做任何特别的事情,它应该只是工作.

当我有一个带有这个控制器的全新rails应用程序:

class FooController < ApplicationController
  def index
    raise "error"
  end
end
Run Code Online (Sandbox Code Playgroud)

然后去 http://127.0.0.1:3000/foo/

看到堆栈跟踪的异常.

您可能无法在控制台日志中看到整个堆栈跟踪,因为Rails(从2.3开始)过滤来自框架本身的堆栈跟踪中的行.

请参阅config/initializers/backtrace_silencers.rbRails项目

  • 优秀,简洁的答案. (2认同)

hal*_*dan 60

你可以这样做:

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
Run Code Online (Sandbox Code Playgroud)

你在这里做的是创建一个"NotActivated"类,它将作为Exception.使用raise,您可以将"NotActivated"作为异常抛出.rescue_from是使用指定方法捕获异常的方法(在本例中为not_activated).相当长的例子,但它应该告诉你它是如何工作的.

祝愿,
费边

  • “我们很抱歉”页面实际上是您的 Web 服务器的 500 错误处理程序。检查您的 .htaccess 文件,您通常会在那里看到它 (2认同)

Sam*_*rma 11

如果您需要一种更简单的方法来做,并且不想大惊小怪,那么简单的执行可能是:

raise Exception.new('something bad happened!')
Run Code Online (Sandbox Code Playgroud)

这将引发异常,说ee.message = something bad happened!

然后你可以拯救它,因为你正在拯救一般的所有其他例外.

  • 引发或拯救“异常”本身并不是一个好主意,请尝试使用 StandardError 代替。有关详细信息,请参阅此:/sf/ask/703372141/ (3认同)