ruby - 错误处理 : How to throw/catch errors correctly

标签 ruby

我有一个调用另外两个方法的方法:

def first_method
  second_method

  # Don´t call this method when something went wrong before
  third_method
end

second_method 调用其他方法:

def second_method
  fourth_method
  fifth_method
end

假设 fifth_method 有一个 begin/rescue 语句:

def fifth_method
  begin
    # do_something
  rescue Error => e
    # 
  end
end

现在我想避免在 fifth_method 抛出错误时调用 third_method。我/你如何在 Ruby 中最优雅地解决这个问题。

最佳答案

在我看来很明显,但无论如何

def first_method
  begin 
    second_method
  rescue
    return
  end
  third_method
end

这种构造(没有显式异常类型)将捕获 StandartError 异常。

为避免与其他异常相交,您可以创建自己的异常类:

class MyError < StandardError; end

然后使用它

begin 
  second_method
rescue MyError => e
  return
end

请注意,您不应从 Exception 继承异常,因为此类异常来自环境级别,其中 StandardError 的异常旨在处理应用程序级别的错误。

关于ruby - 错误处理 : How to throw/catch errors correctly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12002347/

相关文章:

css - 从 Rails 表单中的 f.submit 中删除按钮样式

sql - 基于计数分组的 Active Record 对象

ruby-on-rails - 如何使用 gsub 替换撇号

ruby-on-rails - 如何处理 Rails 资源路由中的点字符?

ruby - 在 Prawn 中检测新页面

javascript - 用于发布赞成票/反对票的 Ajax(停止页面刷新)

ruby - ruby 中的 urldecode?

ruby - 无法将 HAML 布局与中间人一起使用

ruby-on-rails - Rails Associations - 强大的参数构建

ruby-on-rails - 如何在 Postgres 数据库中存储正则表达式或搜索词并在 Rails Query 中进行评估?