98

我似乎找不到太多关于自定义异常类的信息。

我所知道的

您可以声明您的自定义错误类并让它继承自StandardError,因此它可以是rescued:

class MyCustomError < StandardError
end

这允许您使用以下方法提升它:

raise MyCustomError, "A message"

稍后,在救援时收到该消息

rescue MyCustomError => e
  puts e.message # => "A message"

我不知道的

我想给我的异常一些自定义字段,但我想message从父类继承属性。我发现阅读这个主题不是@message异常类的实例变量,所以我担心我的继承不起作用。

谁能给我更多的细节?我将如何实现具有object属性的自定义错误类?以下是否正确:

class MyCustomError < StandardError
  attr_reader :object
  def initialize(message, object)
    super(message)
    @object = object
  end
end

接着:

raise MyCustomError.new(anObject), "A message"

要得到:

rescue MyCustomError => e
  puts e.message # => "A message"
  puts e.object # => anObject

它会起作用吗,如果起作用,这是正确的做事方式吗?

4

4 回答 4

127

raise已经设置了消息,因此您不必将其传递给构造函数:

class MyCustomError < StandardError
  attr_reader :object

  def initialize(object)
    @object = object
  end
end

begin
  raise MyCustomError.new("an object"), "a message"
rescue MyCustomError => e
  puts e.message # => "a message"
  puts e.object # => "an object"
end

我已替换rescue Exceptionrescue MyCustomError,请参阅为什么在 Ruby 中 `rescue Exception => e` 是一种不好的风格?.

于 2013-04-19T15:31:10.227 回答
11

鉴于Exception所有其他错误都继承自 的 ruby​​ 核心文档,其中陈述了关于#message

返回调用 exception.to_s 的结果。通常这会返回异常的消息或名称。通过提供 to_str 方法,同意在期望字符串的地方使用异常。

http://ruby-doc.org/core-1.9.3/Exception.html#method-i-message

我会选择重新定义to_s/to_str或初始化程序。这是一个示例,我们想以人类可读的方式了解外部服务何时无法执行某项操作。

注意:下面的第二种策略使用 rails 漂亮的字符串方法,例如demodualize,这可能有点复杂,因此在异常中可能不明智。如果需要,您还可以向方法签名添加更多参数。

覆盖#to_s 策略 而不是#to_str,它的工作方式不同

module ExternalService

  class FailedCRUDError < ::StandardError
    def to_s
      'failed to crud with external service'
    end
  end

  class FailedToCreateError < FailedCRUDError; end
  class FailedToReadError < FailedCRUDError; end
  class FailedToUpdateError < FailedCRUDError; end
  class FailedToDeleteError < FailedCRUDError; end
end

控制台输出

begin; raise ExternalService::FailedToCreateError; rescue => e; e.message; end
# => "failed to crud with external service"

begin; raise ExternalService::FailedToCreateError, 'custom message'; rescue => e; e.message; end
# => "failed to crud with external service"

begin; raise ExternalService::FailedToCreateError.new('custom message'); rescue => e; e.message; end
# => "failed to crud with external service"

raise ExternalService::FailedToCreateError
# ExternalService::FailedToCreateError: failed to crud with external service

覆盖 #initialize 策略

这是最接近我在 rails 中使用的实现的策略。如上所述,它使用demodualizeunderscorehumanize ActiveSupport方法。但这可以很容易地删除,就像之前的策略一样。

module ExternalService
  class FailedCRUDError < ::StandardError
    def initialize(service_model=nil)
      super("#{self.class.name.demodulize.underscore.humanize} using #{service_model.class}")
    end
  end

  class FailedToCreateError < FailedCRUDError; end
  class FailedToReadError < FailedCRUDError; end
  class FailedToUpdateError < FailedCRUDError; end
  class FailedToDeleteError < FailedCRUDError; end
end

控制台输出

begin; raise ExternalService::FailedToCreateError; rescue => e; e.message; end
# => "Failed to create error using NilClass"

begin; raise ExternalService::FailedToCreateError, Object.new; rescue => e; e.message; end
# => "Failed to create error using Object"

begin; raise ExternalService::FailedToCreateError.new(Object.new); rescue => e; e.message; end
# => "Failed to create error using Object"

raise ExternalService::FailedCRUDError
# ExternalService::FailedCRUDError: Failed crud error using NilClass

raise ExternalService::FailedCRUDError.new(Object.new)
# RuntimeError: ExternalService::FailedCRUDError using Object

演示工具

这是一个演示,展示了上述实现的救援和消息传递。引发异常的类是 Cloudinary 的假 API。只需将上述策略之一转储到您的 Rails 控制台中,然后执行此操作。

require 'rails' # only needed for second strategy 

module ExternalService
  class FailedCRUDError < ::StandardError
    def initialize(service_model=nil)
      @service_model = service_model
      super("#{self.class.name.demodulize.underscore.humanize} using #{@service_model.class}")
    end
  end

  class FailedToCreateError < FailedCRUDError; end
  class FailedToReadError < FailedCRUDError; end
  class FailedToUpdateError < FailedCRUDError; end
  class FailedToDeleteError < FailedCRUDError; end
end

# Stub service representing 3rd party cloud storage
class Cloudinary

  def initialize(*error_args)
    @error_args = error_args.flatten
  end

  def create_read_update_or_delete
    begin
      try_and_fail
    rescue ExternalService::FailedCRUDError => e
      e.message
    end
  end

  private def try_and_fail
    raise *@error_args
  end
end

errors_map = [
  # Without an arg
  ExternalService::FailedCRUDError,
  ExternalService::FailedToCreateError,
  ExternalService::FailedToReadError,
  ExternalService::FailedToUpdateError,
  ExternalService::FailedToDeleteError,
  # Instantiated without an arg
  ExternalService::FailedCRUDError.new,
  ExternalService::FailedToCreateError.new,
  ExternalService::FailedToReadError.new,
  ExternalService::FailedToUpdateError.new,
  ExternalService::FailedToDeleteError.new,
  # With an arg
  [ExternalService::FailedCRUDError, Object.new],
  [ExternalService::FailedToCreateError, Object.new],
  [ExternalService::FailedToReadError, Object.new],
  [ExternalService::FailedToUpdateError, Object.new],
  [ExternalService::FailedToDeleteError, Object.new],
  # Instantiated with an arg
  ExternalService::FailedCRUDError.new(Object.new),
  ExternalService::FailedToCreateError.new(Object.new),
  ExternalService::FailedToReadError.new(Object.new),
  ExternalService::FailedToUpdateError.new(Object.new),
  ExternalService::FailedToDeleteError.new(Object.new),
].inject({}) do |errors, args|
  begin 
    errors.merge!( args => Cloudinary.new(args).create_read_update_or_delete)
  rescue => e
    binding.pry
  end
end

if defined?(pp) || require('pp')
  pp errors_map
else
  errors_map.each{ |set| puts set.inspect }
end
于 2016-08-20T10:02:07.700 回答
6

你的想法是对的,但你称呼它的方式是错误的。它应该是

raise MyCustomError.new(an_object, "A message")
于 2013-04-19T14:20:04.663 回答
5

我想做类似的事情。我想将一个对象传递给#new,并根据对传递对象的一些处理来设置消息。以下作品。

class FooError < StandardError
  attr_accessor :message # this is critical!
  def initialize(stuff)
    @message = stuff.reverse
  end
end

begin
  raise FooError.new("!dlroW olleH")
rescue FooError => e
  puts e.message #=> Hello World!
end

请注意,如果您不声明attr_accessor :message,则它将不起作用。解决 OP 的问题,您还可以将消息作为附加参数传递并存储您喜欢的任何内容。关键部分似乎覆盖了#message。

于 2016-02-09T19:16:57.707 回答