Take the 2-minute tour ×

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?

share|improve this question

1 Answer 1

up vote 9 down vote accepted

From 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


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

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.

share|improve this answer
So it's not "anti-pattern" to add an errors on before_save. Good to know, thanks. –  Zequez Feb 1 '12 at 5:15
@Zequez: I don't think it is an anti-pattern, just don't use your before_save for validation. –  mu is too short Feb 1 '12 at 5:21
I know, but for some reason I feel like the errors object should be used just for validation errors. –  Zequez Feb 2 '12 at 7:48
A validation failure is an error but not the only type of error that the user will be interested in. Telling them that something went wrong that wasn't their fault is better than handing them a 500 page. –  mu is too short Feb 2 '12 at 8:00
I must be crazy because this just does not work for me. Surely the validations are complete by the time before_save is called, thus you can't add to errors and have it fail validation? –  Tim Fletcher Jun 20 '12 at 22:44

Your Answer


