Custom exceptions on validations

I think it would be a good idea if it was possible to define custom
exceptions that validation methods throw, instead of always throwing
ActiveRecord::RecordInvalid.

The syntax could be something like this:

validates_presence_of :name, :exception => SomeException

It would allow for much more elegant code, in cases where it is
necessary to identify which validation failed. What do you think?

I wouldn't mind trying to implement this (in fact I'm very eager to do
so!) although I'd need some guidance.

Regards,
André Silva

Interesting idea. I’d suggest making sure that the exception classes are subclasses of ActiveRecord::RecordInvalid, so that rescue clauses can either care about the specific validation or not.

Which exception would you raise if 2 validations fail ?

Robert Pankowecki

Great question although I have no set answer :frowning: Maybe I should raise
an exception for the "first" validation that fails?

I feel that the conventional use case of validations is returning the
object with the errors attribute(s) set to let you know which parts
failed. A validation is used to confirm that user data entry conforms
to necessary constraints, in normal processing (ie. a controller
calling record.save) the exceptions are not raised and you need to
deal with failure.

If the code is being run in a programmatic way, that is the data entry
is not coming from a user, and you are using record.save! it, in my
read of the Rails conventions, be considered a programmatic error if
it resulted in an exception. Your calling code should be giving valid
values and not relying on exceptions to determine next action. The
exception raised here should probably halt execution, or at the least
send out crazy warnings (including examination of the record.errors
object).

Your use case may vary :slight_smile:

You are correct that my code is being run in a programmatic way, the
data entry is not coming from a user but is instead coming from
another system. Validations are a very powerful (and easy) way to make
sure that the data that comes from the foreign system is correct.
Still, I have to act upon invalid data in a programmatic way, i.e. I
have to reply to the foreign system (and not just by giving it the
errors hash).
I could make sure that only valid values are given, but I would have
to validate it on another layer, without relying on the powerful
validation system provided by ActiveRecord.

I know my use case is different than 99% of the typical usage
scenarios. Still, I think this addition would improve the
extensibility of validations.

Regards,
André Silva