Rails Exception Handling
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.
Exceptions that happen as a part of saving/creating a model
I use the ActiveRecord callbacks after_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.
Remember that if your before_save method returns false, the save will fail.
Exceptions for other model methods
All the usual methods are available:
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?
begin
Some code
rescue =>e
@error= e.message
Exception Handling
end
在视图中
<%= @error %>
链接地址: http://www.djcxy.com/p/25850.html
上一篇: 如何发信号“尚未实施”?
下一篇: Rails异常处理