Cuando hay un error al procesar un archivo before_save, después de la validación, ¿debo generar una excepción o devolver falso y agregar un 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?

preguntado el 01 de febrero de 12 a las 03:02

1 Respuestas

Desde el Guía de validaciones de registros activos y devoluciones de llamada:

Si alguna antes de 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 si no lo hacen.

Respondido el 05 de Septiembre de 13 a las 20:09

So it's not "anti-pattern" to add an errors on before_save. Good to know, thanks. - Zequez

@Zequez: I don't think it is an anti-pattern, just don't use your before_save para validación. - mu es demasiado corto

I know, but for some reason I feel like the errors object should be used just for validation errors. - Zequez

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 es demasiado corto

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

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.