In my “create” action on a form, I successfully save (1) MyObject to my local database and (2) OtherObject to a third-party database via its Ruby API. When something goes wrong with the save to the third party, I get an error in the form of a Ruby exception.
My question is: How do I stop the form submit and report the exception message to the client?
If this is not possible, what would be the best alternative?
Depending on whether you want to rollback your local database call, you might want to consider using Transactions. Something along these lines:
This will store the exception message into the
flashwhich you can use to display to the user. Note Do not store the entireExceptionobject into theflash, you will definitely see overflow errors if your exception objects are too big.If you’re not too concerned about rolling back the
MyObjectcreation, then you can just use a simplebegin…rescuesimilar to what I showed in my example. You may need to determine whether you want to do aredirect_toorrenderdepending on whether an exception occurred, but you can always conditionally determine that based on whetherflash[:exception].nil?istrueor not.