class
Active Record RecordInvalid
Raised by save! and create! when the record is invalid. Use the record method to retrieve the record which did not validate.
begin complex_operation_that_calls_save!_internally rescue ActiveRecord::RecordInvalid => invalid puts invalid.record.errors end
Register or
log in
to add new notes.
jqr -
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
noxyu3m -
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.
schmidt -
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.