在 Ruby 中捕获异常后重新引发(相同的异常)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23770924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:30:04  来源:igfitidea点击:

Reraise (same exception) after catching an exception in Ruby

rubyexception

提问by Hommer Smith

I am trying to improve my Ruby skills by catching exceptions. I want to know if it is common to reraise the same kind of exception when you have several method calls. So, would the following code make sense? Is it ok to reraise the same kind of exception, or should I not catch it on the process method?

我正在尝试通过捕获异常来提高我的 Ruby 技能。我想知道当您有多个方法调用时,重新引发相同类型的异常是否很常见。那么,下面的代码有意义吗?是否可以重新引发相同类型的异常,或者我不应该在 process 方法中捕获它?

class Logo
  def process
    begin
      @processed_logo = LogoProcessor::create_image(self.src)
    rescue CustomException
      raise CustomException
    end
  end
end

module LogoProcessor
  def self.create_image
    raise CustomException if some_condition
  end
end

回答by Matheus Moreira

Sometimes we just want to know an error happened, without having to actually handlethe error.

有时我们只想知道发生了错误,而不必实际处理错误。

It is often the case that the one responsible for handling errors is user of the object: the caller. What if we are interested in the error, but don't want to assume that responsibility? We rescue the error, do whatever we need to do and then propagate the signal up the stack as if nothing had happened.

通常情况下,负责处理错误的是对象的用户:调用者。如果我们对错误感兴趣,但不想承担责任怎么办?我们挽救错误,做任何我们需要做的事情,然后将信号向上传播到堆栈,就好像什么都没发生过一样。

For example, what if we wanted to log the error message and then let the caller deal with it?

例如,如果我们想记录错误信息,然后让调用者处理它怎么办?

begin
  this_will_fail!
rescue Failure => error
  log.error error.message
  raise
end

Calling raisewithout any arguments will raise the last error. In our case, we are re-raising error.

raise不带任何参数调用将引发最后一个错误。在我们的例子中,我们正在重新加注error

In the example you presented in your question, re-raising the error is simply not necessary. You could simply let it propagate up the stack naturally. The only difference in your example is you're creating a new error object and raising it instead of re-raising the last one.

在您在问题中提供的示例中,根本没有必要重新引发错误。你可以简单地让它自然地向上传播。您的示例中唯一的区别是您正在创建一个新的错误对象并引发它而不是重新引发最后一个。

回答by FreePender

This will raise the same type of error as the original, but you can customize the message.

这将引发与原始错误类型相同的错误,但您可以自定义消息。

rescue StandardError => e
  raise e.class, "Message: #{e.message}"

回答by Aeramor

Not really, the question you need to ask yourself is where do you need this info? In your case I would catch it locally and return false (noting the call failed).

不是真的,你需要问自己的问题是你在哪里需要这些信息?在您的情况下,我会在本地捕获它并返回 false(注意调用失败)。