DEV Community

Discussion on: Smarter Rails Services with Active Model Modules

Collapse
 
sophiedebenedetto profile image
Sophie DeBenedetto

Hi,

So the use of ActiveModel::Validations gives our instance of PurchaseHandler access to the #errors method. If you look at the ProductQualityValidator, you can see that that it is operating on record. This record attribute of our validator refers to the PurchaseHandler instance that we are validating. We add errors to our instance via record.errors.add. We can call purchase_handler.errors to see any errors that were added to the instance by the validator. You can use these errors however you want--render them in a view for example or use them to populate a JSON api response.

The validator is invoked by the after_initialize :valid? callback that we defined in our PurchaseHandler class.

Collapse
 
ipmsteven profile image
Yunlei Liu • Edited

Thanks for the reply.
I think what you mentioned is the validation error, or validate the input for service.

How about an exception is raised when service object is doing the work?
Like item is out of stock when try to purchase, no item found when db fetch, etc.

Some of the exceptions we can avoid by pre-validate the input parameter, but some can only happen when we execute the code

Thanks

Thread Thread
 
sophiedebenedetto profile image
Sophie DeBenedetto

Ah okay I see what you're saying. I think you can choose how to raise and handle exceptions as you would in any Rails model or service without violating the basic design outlined here. You have a few options available to you--use additional custom validators to add errors to the PurchaseHandler instance, or raise custom errors. I wrote another post on a pattern of custom error handling in similar service objects within a Rails API on my personal blog if you want to check it out: thegreatcodeadventure.com/rails-ap...

Thread Thread
 
ipmsteven profile image
Yunlei Liu

Thanks!