Active Record RecordInvalid

Raised by {ActiveRecord::Base#save!}[rdoc-ref:Persistence#save!] and {ActiveRecord::Base#create!}[rdoc-ref:Persistence::ClassMethods#create!] when the record is invalid. Use the #record method to retrieve the record which did not validate.

begin
  complex_operation_that_internally_calls_save!
rescue ActiveRecord::RecordInvalid => invalid
  puts invalid.record.errors
end
Show files where this class is defined (1 file)
Register or log in to add new notes.
February 14, 2009
1 thank

Clear and simple rescue

noxyu3m, your code is rescuing all exceptions, not just ActiveRecord::RecordInvalid.

I think this syntax is a bit more clear than using the global variable.

def create
  @model = Model.new(params[:model)
  @model.save!
rescue => err                          # rescues all exceptions
  logger.error(err.to_s)
end
February 14, 2009
0 thanks

Simple rescue

Take it easy:

def create
  @model = Model.new(params[:model)
  @model.save!
rescue
  logger.error(!$.to_s)
end

Global variable !$ refers to the Exception object.

April 15, 2009
0 thanks

Using global $! to address exception

@noxyu3m: Your code is actually syntactically wrong. The global is called $!

Your code should have been:

def create
  @model = Model.new(params[:model)
  @model.save!
rescue
  logger.error($!.to_s)
end

Although I would prefer

def create
  @model = Model.new(params[:model)
  @model.save!
rescue ActiveRecord::RecordInvalid
  logger.error($!.to_s)
end

to only catch expected exceptions, just like the documentation proposed.