How to rescue model transaction and show the user an error? How to rescue model transaction and show the user an error? ruby ruby

How to rescue model transaction and show the user an error?


def exchange_status_with(address)  ActiveRecord::Base.transaction do   self.save!   address.save!  endrescue ActiveRecord::RecordInvalid => exception  # do something with exception hereend

FYI, an exception looks like:

#<ActiveRecord::RecordInvalid: Validation failed: Email can't be blank>

And:

exception.message# => "Validation failed: Email can't be blank"

Side note, you can change self.save! to save!


Alternate solution if you want to keep your active model errors:

class MyCustomErrorClass < StandardError; enddef exchange_status_with(address)  ActiveRecord::Base.transaction do   raise MyCustomErrorClass unless self.save   raise MyCustomErrorClass unless address.save  endrescue MyCustomErrorClass  # here you have to check self.errors OR address.errorsend