Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Handling Failure | Prefer top-level rescue clause

概要

Prefer top-level rescue clause

前提

Confident Rubyではメソッド内の処理を次のように分類しています。
・Collecting Inputs(引数チェック、変換など)
・Performing Work(主処理)
・Delivering Output(戻り値に関わる処理)
・Handling Failure(例外処理)

当記事は上記のうち、Handling Failureに関する話です。

詳細

状況

メソッドが begin/rescue/end ブロックを持つ場合

概要

Rubyのトップレベルで rescue句のシンタックスを利用するように変更する

理由

このイディオムはメソッドの"成功シナリオ" と "失敗シナリオ" 2つの部分の見た目をクリアに分割する

サンプルコード仕様

メッセージを出力するメソッドを作成します。
メッセージが「hoge」だった場合のみ例外が発生します。

サンプル1:例外処理を begin/rescue/end で行います
サンプル2:例外処理を トップレベルの rescueで行います

サンプルコードその1

def puts_message_unless_hoge(msg)
  begin
    fail 'invalid msg hoge' if msg == 'hoge'
    puts msg
  rescue => e
    puts "you must not use 'hoge'"
  end
end

puts_message_unless_hoge "hige"
puts_message_unless_hoge "hoge"

出力

hige
you must not use 'hoge'

サンプルコードその1

def puts_message_unless_hoge(msg)
  fail 'invalid msg hoge' if msg == 'hoge'
  puts msg

rescue => e
  puts "you must not use 'hoge'"
end

puts_message_unless_hoge "hige"
puts_message_unless_hoge "hoge"

出力

hige
you must not use 'hoge'