Today I Learned

validate! can raise various classes of exceptions

class ActiveRecord::Base and module ActiveModel::Validations raise different exceptions on failed validate!

consider the following classes:

class Foo
  include ActiveModel::Validations

  validates :foo, presence: true

  def foo
    nil
  end
end

class Organisation < ActiveRecord::Base
  validates :name, presence: true
end

Take a look on classes of raised exceptions:

[2] pry(#<Api::V1::HooksController>)> Foo.new.validate!
ActiveModel::ValidationError: Validation failed: Foo can't be blank
from /Users/bartoszmaka/.asdf/installs/ruby/2.6.2/lib/ruby/gems/2.6.0/gems/activemodel-6.0.0.rc1/lib/active_model/validations.rb:412:in `raise_validation_error'
[3] pry(#<Api::V1::HooksController>)> Organisation.new.validate!
ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
from /Users/bartoszmaka/.asdf/installs/ruby/2.6.2/lib/ruby/gems/2.6.0/gems/activerecord-6.0.0.rc1/lib/active_record/validations.rb:80:in `raise_validation_error'

The highest common ancestor of those classes is StandardError

[4] pry(#<Api::V1::HooksController>)> ActiveModel::ValidationError.ancestors
=> [ActiveModel::ValidationError,
 StandardError,
 Exception,
 ActiveSupport::Dependencies::Blamable,
 ActiveSupport::ToJsonWithActiveSupportEncoder,
 Object,
 ActiveSupport::Tryable,
 ActiveSupport::Dependencies::Loadable,
 JSON::Ext::Generator::GeneratorMethods::Object,
 PP::ObjectMixin,
 Kernel,
 BasicObject]

[5] pry(#<Api::V1::HooksController>)> ActiveRecord::RecordInvalid.ancestors
=> [ActiveRecord::RecordInvalid,
 ActiveRecord::ActiveRecordError,
 StandardError,
 Exception,
 ActiveSupport::Dependencies::Blamable,
 ActiveSupport::ToJsonWithActiveSupportEncoder,
 Object,
 ActiveSupport::Tryable,
 ActiveSupport::Dependencies::Loadable,
 JSON::Ext::Generator::GeneratorMethods::Object,
 PP::ObjectMixin,
 Kernel,
 BasicObject]

If you’re using form objects - chances are, that you’re importing ActiveModel::Validations. Make sure that you rescue_from the proper exceptions.

Used versions: ruby 2.6.2p47, Rails 6.0.0.rc1