2019-11-12

【Ruby】rescueした例外のmessageを上書きしてre-raiseする

rescueした例外のmessageを上書きしてre-raiseしたい場合、Exception#exception を使うとスッキリ書ける。

https://docs.ruby-lang.org/ja/latest/method/Exception/i/exception.html

引数を指定しない場合は self を返します。
引数を指定した場合 自身のコピー を生成し Exception#message 属性を error_message にして返します。

# exception_test.rb
def override_exception_message_and_reraise
  begin
    raise RuntimeError.new('abc')
  rescue => e
    raise e.exception('xyz')
  end
end

次のテストはpassする。

# spec/exception_test_spec.rb
require_relative '../exception_test.rb'

RSpec.describe do
  it do
    expect { override_exception_message_and_reraise }.to raise_error(RuntimeError, 'xyz')
  end
end