Ruby-on-rails Rails 异常处理
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3128580/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails Exception Handling
提问by felix
How can I send the error messages that are happening in the model code back to the view. I mean. I have a
如何将模型代码中发生的错误消息发送回视图。我的意思是。我有一个
begin
Some code
rescue
Exception Handling
end
now error occurs and in the rescue, I would like to send a message back to the controller, so that it ll get displayed in the view. Do I have to use a variable, which has to contain a number of error messages that occurs in one request, concatenate them and send it back to controller, so that I can display it in the view?. Rails already shows some error messages like field can't be blank. I am asking about the other exceptions, which occurs in the functions that are present in the model code.
现在发生错误,在救援中,我想向控制器发送一条消息,以便它显示在视图中。我是否必须使用一个变量,该变量必须包含在一个请求中发生的许多错误消息,将它们连接起来并将其发送回控制器,以便我可以在视图中显示它?。Rails 已经显示了一些错误消息,例如字段不能为空。我在询问其他异常,这些异常发生在模型代码中存在的函数中。
采纳答案by Larry K
Exceptions that happen as a part of saving/creating a model
作为保存/创建模型的一部分发生的异常
I use the ActiveRecord callbacksafter_validation, after_validation_on_create, and before_save (depending on the circumstance), to obtain any extra data and verify that everything is ready to be saved. Then, if any problems, I store the exception in errors[:base] using add_to_base. That way the view will display the error msg in the same way it displays any other validation errors.
我使用 ActiveRecord回调after_validation、after_validation_on_create 和 before_save(取决于具体情况)来获取任何额外数据并验证所有内容是否已准备好保存。然后,如果有任何问题,我会使用add_to_base将异常存储在 errors[:base] 中。这样,视图将以与显示任何其他验证错误相同的方式显示错误消息。
Remember that if your before_save method returns false, the save will fail.
请记住,如果您的 before_save 方法返回 false,则保存将失败。
Exceptions for other model methods
其他模型方法的例外
All the usual methods are available:
所有常用方法都可用:
- Raise a specific exception that the controller will catch. The exception can include an error number that the view translates to an error msg. Or the model can export an error_num to error_msg hash
- Return an error code as a return parameter of the method. Eg if you want to also use the Flash to give a positive msg when things work, you can return a msg_code. Then have negative msg codes for errors and positive codes for different types of success.
- Establish an @error (or whatever) instance variable to be checked by the caller.
- 引发控制器将捕获的特定异常。异常可以包括错误号,视图将其转换为错误消息。或者模型可以导出一个 error_num 到 error_msg 哈希
- 返回错误代码作为方法的返回参数。例如,如果您还想在工作正常时使用 Flash 给出肯定的 msg,您可以返回一个 msg_code。然后有错误的负 msg 代码和不同类型成功的正代码。
- 建立一个@error(或其他)实例变量以供调用者检查。
回答by nathanvda
An example of what i do in my own code:
我在自己的代码中所做的一个例子:
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
end
结尾
Does that help?
这有帮助吗?
回答by Salil
begin
Some code
rescue =>e
@error= e.message
Exception Handling
end
in views
在视图中
<%= @error %>
回答by Sandeep Leo
begin
some code
rescue StandardError => ex
flash[:error] = "#{ex}"
render :index
end
回答by Haris Krajina
Set exception handler in ApplicationController
设置异常处理程序 ApplicationController
class ApplicationController < ActionController::Base
rescue_from Exception, :with => :handle_exception
def handle_exception
flash[:error] = error.message
redirect_to request.referer || root_path
end
end
This is general example, you can specify types of exception e.g. rescue_from ActiveRecord::RecordNotFound, ActiveRecord::RecordInvalidetc.
这是一般示例,您可以指定异常类型,例如rescue_from ActiveRecord::RecordNotFound, ActiveRecord::RecordInvalid等。

