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

我想引发一个异常,这样它就可以做与普通 Rails 异常相同的事情。特别是,在开发模式中显示异常和堆栈跟踪,并在生产模式中显示“对不起,但有些地方出错了”页面。

我尝试了以下方法:

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

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

159228 次浏览

You can do it like this:

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

You don't have to do anything special, it should just be working.

When I have a fresh rails app with this controller:

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

and go to http://127.0.0.1:3000/foo/

I am seeing the exception with a stack trace.

You might not see the whole stacktrace in the console log because Rails (since 2.3) filters lines from the stack trace that come from the framework itself.

See config/initializers/backtrace_silencers.rb in your Rails project

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.