Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If I have, for example, an image that pass all the validations, like, size, dimensions, type, etc, but when I have to process it, for some unknown reason ImageMagick throws an error anyway... how should I handle that?

like image 324
Zequez Avatar asked Dec 12 '22 05:12

Zequez


1 Answers

For Rails 4 and earlier the Active Record Validations and Callbacks Guide:

If any before callback method returns exactly false or raises an exception, the execution chain gets halted and a ROLLBACK is issued [...]

So you can either let the exception bubble up into ActiveRecord or you can trap it yourself, translate it to something that makes sense within the context of your application, and return false. You can register errors inside a before_save callback 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 the ImageMagick errors into something that makes sense to the end user then trapping and translating the ImageMagick exception (as in do_magick_things) would probably make the most sense; converting the exception into an error message also allows the caller to use save! if they want exceptions or save if they don't.

like image 120
mu is too short Avatar answered Apr 13 '23 01:04

mu is too short