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.
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.
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).
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.