fel*_*lix 16 exception-handling ruby-on-rails
如何将模型代码中发生的错误消息发送回视图.我的意思是.我有一个
begin
Some code
rescue
Exception Handling
end
Run Code Online (Sandbox Code Playgroud)
现在出现错误,在救援中,我想将一条消息发送回控制器,以便它在视图中显示.我是否必须使用一个变量,该变量必须包含一个请求中出现的大量错误消息,将它们连接起来并将其发送回控制器,以便我可以在视图中显示它?Rails已经显示一些错误消息,如字段不能为空.我问的是其他异常,它们出现在模型代码中的函数中.
nat*_*vda 12
我在自己的代码中做的一个例子:
def create
@letter = Letter.new(params[:id])
begin
@letter.do_something_that_could_throw_an_exception
flash[:notice] = I18n.translate('letter.success_create')
rescue => e
logger.error "letter_controller::create => exception #{e.class.name} : #{e.message}"
flash[:error] = "#{I18n.translate('letter.letter_create_failed')}<br/>Detailed error: #{e.message}"
ExceptionNotifier.deliver_exception_notification(e, self, request)
# redirect somewhere sensible?
end
end
Run Code Online (Sandbox Code Playgroud)
结束
这有帮助吗?
begin
Some code
rescue =>e
@error= e.message
Exception Handling
end
Run Code Online (Sandbox Code Playgroud)
在视图中
<%= @error %>
Run Code Online (Sandbox Code Playgroud)
作为保存/创建模型的一部分而发生的异常
我使用ActiveRecord 回调 after_validation,after_validation_on_create和before_save(取决于具体情况)来获取任何额外数据并验证是否已准备好保存所有内容.然后,如果有任何问题,我使用add_to_base将异常存储在错误[:base]中.这样,视图将以与显示任何其他验证错误相同的方式显示错误消息.
请记住,如果您的before_save方法返回false,则保存将失败.
其他模型方法的例外情况
所有常用方法都可用:
设置异常处理程序ApplicationController
class ApplicationController < ActionController::Base
rescue_from Exception, :with => :handle_exception
def handle_exception(error)
flash[:error] = error.message
redirect_to request.referer || root_path
end
end
Run Code Online (Sandbox Code Playgroud)
这是一般示例,您可以指定异常类型,例如rescue_from ActiveRecord::RecordNotFound, ActiveRecord::RecordInvalid等。