获取现有Rails错误类的列表以供重用/继承

ber*_*kes 21 error-handling custom-exceptions ruby-on-rails-3

我经常需要抛出一个自定义(错误)错误.就像由于参数不匹配而无法找到资源时.

我更喜欢抛出现有错误,或抛出从现有错误继承的错误.这样,我不会引入已经定义的错误类,并且可以完美地使用(DRY).但它也允许保持措辞和风格相同,通过继承和简单地改变一两个字来澄清与原始错误的差异.

例如:

Foo.new
Foo.some_external_id = nil
Foo.fetch_external_resource
# => InvalidOptions: Calling Foo#fetch_external_resource with nil is invalid
Run Code Online (Sandbox Code Playgroud)

我很确定已经定义了这样的错误.事实上,在通过多行代码阅读后,我发现我的MongoID驱动程序已经存在Mongoid::Errors::InvalidOptions: Calling Document#find with nil is invalid.

Ruby Core和Ruby on Rails中是否有可用的错误类列表?有没有办法为您当前的项目获得这样的列表?

重新使用和/或继承现有错误是否很聪明,或者我应该维护自己的自定义设置?

wby*_*ung 46

虽然这个列表可能会改变,但最好仍然使用Ryan的解决方案,Rails 4的列表(仅限Rails类而不是其他宝石):

AbstractController::ActionNotFound
AbstractController::DoubleRenderError
AbstractController::Error
AbstractController::Helpers::ClassMethods::MissingHelperError
ActionController::ActionControllerError
ActionController::BadRequest
ActionController::InvalidAuthenticityToken
ActionController::MethodNotAllowed
ActionController::MissingFile
ActionController::NotImplemented
ActionController::ParameterMissing
ActionController::RedirectBackError
ActionController::RenderError
ActionController::RoutingError
ActionController::SessionOverflowError
ActionController::UnknownController
ActionController::UnknownFormat
ActionController::UnknownHttpMethod
ActionController::UnpermittedParameters
ActionController::UrlGenerationError
ActionDispatch::Cookies::CookieOverflow
ActionDispatch::IllegalStateError
ActionDispatch::Journey::Router::RoutingError
ActionDispatch::ParamsParser::ParseError
ActionDispatch::RemoteIp::IpSpoofAttackError
ActionDispatch::Session::SessionRestoreError
ActionView::Helpers::NumberHelper::InvalidNumberError
ActiveModel::ForbiddenAttributesError
ActiveModel::MissingAttributeError
ActiveRecord::ActiveRecordError
ActiveRecord::AdapterNotFound
ActiveRecord::AdapterNotSpecified
ActiveRecord::AssociationTypeMismatch
ActiveRecord::AttributeAssignmentError
ActiveRecord::ConfigurationError
ActiveRecord::ConnectionNotEstablished
ActiveRecord::ConnectionTimeoutError
ActiveRecord::DangerousAttributeError
ActiveRecord::DeleteRestrictionError
ActiveRecord::DuplicateMigrationNameError
ActiveRecord::DuplicateMigrationVersionError
ActiveRecord::EagerLoadPolymorphicError
ActiveRecord::HasAndBelongsToManyAssociationForeignKeyNeeded
ActiveRecord::HasManyThroughAssociationNotFoundError
ActiveRecord::HasManyThroughAssociationPointlessSourceTypeError
ActiveRecord::HasManyThroughAssociationPolymorphicSourceError
ActiveRecord::HasManyThroughAssociationPolymorphicThroughError
ActiveRecord::HasManyThroughCantAssociateNewRecords
ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection
ActiveRecord::HasManyThroughCantDissociateNewRecords
ActiveRecord::HasManyThroughNestedAssociationsAreReadonly
ActiveRecord::HasManyThroughSourceAssociationNotFoundError
ActiveRecord::HasOneThroughCantAssociateThroughCollection
ActiveRecord::IllegalMigrationNameError
ActiveRecord::ImmutableRelation
ActiveRecord::InvalidForeignKey
ActiveRecord::InverseOfAssociationNotFoundError
ActiveRecord::IrreversibleMigration
ActiveRecord::MultiparameterAssignmentErrors
ActiveRecord::NestedAttributes::TooManyRecords
ActiveRecord::PendingMigrationError
ActiveRecord::PreparedStatementInvalid
ActiveRecord::ReadOnlyAssociation
ActiveRecord::ReadOnlyRecord
ActiveRecord::RecordInvalid
ActiveRecord::RecordNotDestroyed
ActiveRecord::RecordNotFound
ActiveRecord::RecordNotSaved
ActiveRecord::RecordNotUnique
ActiveRecord::Rollback
ActiveRecord::SerializationTypeMismatch
ActiveRecord::StaleObjectError
ActiveRecord::StatementInvalid
ActiveRecord::SubclassNotFound
ActiveRecord::Tasks::DatabaseAlreadyExists
ActiveRecord::Tasks::DatabaseNotSupported
ActiveRecord::ThrowResult
ActiveRecord::TransactionIsolationError
ActiveRecord::Transactions::TransactionError
ActiveRecord::UnknownAttributeError
ActiveRecord::UnknownMigrationVersionError
ActiveRecord::UnknownPrimaryKey
ActiveRecord::WrappedDatabaseException
ActiveSupport::JSON::Encoding::CircularReferenceError
ActiveSupport::MessageVerifier::InvalidSignature
ActiveSupport::SafeBuffer::SafeConcatError
ActiveSupport::XMLConverter::DisallowedType
Run Code Online (Sandbox Code Playgroud)


Rya*_*yan 25

这里有一个基本上足够的解决方案:http://www.ruby-forum.com/topic/158088

由于这个问题没有答案,但是在Google搜索结果中排在最前面,我决定将弗雷德里克·张的解决方案包括在一个rake任务中并在此处发布.

删除lib/tasks/exceptions.rake中的以下内容

namespace :exceptions do
  task :list => :environment do
    exceptions = []

    ObjectSpace.each_object(Class) do |k|
      exceptions << k if k.ancestors.include?(Exception)
    end

    puts exceptions.sort { |a,b| a.to_s <=> b.to_s }.join("\n")
  end
end
Run Code Online (Sandbox Code Playgroud)

运行它:

bundle exec rake exceptions:list
Run Code Online (Sandbox Code Playgroud)

如果您仍然使用Rails 2,或者不使用Bundler,请不要使用 bundle exec

这份清单可能已经足够,但并非详尽无遗.例如,定义的ActiveResource几个例外,如ActiveResource::ConnectionErrorActiveResource::TimeoutError当我运行这个任务没有出现.也许别人可以告诉我为什么.


lob*_*ati 5

由于ActiveSupport,Rails中提供了一个更短的选项:

puts Exception.descendants.sort_by(&:name)
Run Code Online (Sandbox Code Playgroud)

您还可以查看源,以了解他们如何处理它。