访问Rescue Block中的错误消息

时间:2016-06-21 22:09:50

标签: ruby

有没有办法在救援块中以字符串形式访问错误消息?例如:

def foo
  raise RuntimeError, "This is an error"
end

def bar
  begin
    foo
  rescue RuntimeError
    puts "Rescued"
  end
end

bar

有没有办法从救援区获取"This is an error"?像这样:

...
rescue RuntimeError
    puts <error-message>
end
...

1 个答案:

答案 0 :(得分:5)

您需要指定一个变量来存储错误

def foo
  raise RuntimeError, "This is an error"
end

def bar
  begin
    foo
  rescue RuntimeError => ex
    puts "Rescued #{ex.message}"
  end
end