When there is an error processing the before_save file after checking, should I raise an exception or return false and add an error?

If I have, for example, an image that passes all the checks, for example, size, dimensions, type, etc., but when I have to process it, for some unknown reason, ImageMagick still causes an error ... as it should Am I dealing with this?

+4
source share
1 answer

In the Active Records Verification and Callbacks Guide :

If any callback method returns exactly false or throws an exception, the execution chain stops and returns ROLLBACK [...]

Thus, you can either eliminate the appearance of bubbles in ActiveRecord, or trap it yourself, transfer it to something that makes sense in the context of your application, and return false . You can log errors inside the before_save , so something like this might make sense:

 before_save :do_magick_things private def do_magick_things # ImageMagick stuff... true rescue ImageMagickError, FatalImageMagickError => e errors.add(:base, 'Some sort of sensible version of e.message') false end 

If you can translate ImageMagick errors into something that makes sense to the end user, then do_magick_things and translating the ImageMagick exception (as in do_magick_things ) is likely to make the most sense; Converting an exception to an error message also allows the caller to use save! if they want exceptions or save if they do not.

+12
source

Source: https://habr.com/ru/post/1394111/


All Articles