我如何在Rails中引发exception,使其行为像其他Railsexception?

我想提出一个exception,以便它正常的Railsexception做同样的事情。 特别地,在开发模式下显示exception和堆栈跟踪,并在生产模式下显示“我们很抱歉,但出了问题”页面。

我尝试了以下内容:

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

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

你不必做任何特别的事情,它应该是工作。

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

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

并转到http://127.0.0.1:3000/foo/

我看到一个堆栈跟踪exception 。

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

请参阅Rails项目中的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 

你在这里做的是创build一个类“NotActivated”,将作为例外。 使用raise,你可以抛出“NotActivated”作为例外。 rescue_from是使用指定的方法捕获Exception的方法(在这种情况下是not_activated)。 一个很长的例子,但它应该告诉你它是如何工作的。

最好的祝愿,
法比安

如果你需要一个更简单的方法来做到这一点,并不想大惊小怪,简单的执行可能是:

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

这会引发一个exception,说ee.message = something bad happened!

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