Rails Exception Handling
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? endend
end
Does that help?
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:
- 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.
begin Some coderescue =>e @error= e.message Exception Handlingend
in views
<%= @error %>