17

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.

felix
  • 11,304
  • 13
  • 69
  • 95

5 Answers5

13

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?

nathanvda
  • 49,707
  • 13
  • 117
  • 139
7
begin
       Some code
rescue =>e
       @error= e.message
       Exception Handling
end

in views

<%= @error %>
Salil
  • 46,566
  • 21
  • 122
  • 156
  • Note: this example will only work if the first code section is in the controller. If it is in the model, it won't work. – Larry K Jun 27 '10 at 21:51
7

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:

  1. 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
  2. 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.
  3. Establish an @error (or whatever) instance variable to be checked by the caller.
Larry K
  • 47,808
  • 15
  • 87
  • 140
  • 1
    Given the OP's question I'm not sure that they'll understand your #3. Steve, I think what Larry means for 3 is adding something like attr_reader :error to the class definition, assigning it on error, and thus allowing the caller to retrieve it. But I think his #2 is probably the easiest to implement. – adriandz Jun 28 '10 at 02:03
5

Set exception handler in 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

This is general example, you can specify types of exception e.g. rescue_from ActiveRecord::RecordNotFound, ActiveRecord::RecordInvalid etc.

Haris Krajina
  • 14,824
  • 12
  • 64
  • 81
3
begin
  some code
rescue StandardError => ex      
  flash[:error] = "#{ex}"
  render :index
end
theUtherSide
  • 3,338
  • 4
  • 36
  • 35
  • 1
    But avoid rescuing `Exception` as it is the most generic exception type in Ruby see here why it is a bad practice: http://stackoverflow.com/questions/10048173/why-is-it-bad-style-to-rescue-exception-e-in-ruby – Bruno Peres Jul 15 '16 at 23:31