2016-06-21 9 views
1

レスキューブロック内のエラーメッセージに文字列としてアクセスする方法はありますか?たとえば:レスキューブロック内のエラーメッセージへのアクセス

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 
... 

答えて

3

あなたはまた、例外オブジェクトを取得するには、救助ブロックの内側 `$`グローバルを使用することができます

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

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

にエラーを格納する変数を指定する必要があります!。 – zetetic

関連する問題