2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Ruby: `raise` の書き方 - against Provide an exception class and message as arguments to `raise`.Style/RaiseArgs `

Last updated at Posted at 2019-07-12

raise 処理でRubocopに叱られる

Rubyでraise処理を書いた時に以下のようにしたらRubocopに叱られた。

raise OriginError.new('これは問題です!!')
Provide an exception class and message as arguments to `raise`.Style/RaiseArgs

修正された書き方

以下のように変更したら解決します。

raise OriginError, 'これは問題です!!'

ドキュメントによると、例外クラスのインスタンスを作るより例外クラスとエラーメッセージを raise に渡す方が良い、とのこと。

This cop checks the args passed to fail and raise. For exploded style (default), it recommends passing the exception class and message to raise, rather than construct an instance of the error. It will still allow passing just a message, or the construction of an error with more than one argument.

The exploded style works identically, but with the addition that it will also suggest constructing error objects when the exception is passed multiple arguments.

Class: RuboCop::Cop::Style::RaiseArgs

Rubocopでサポートしているスタイルは2つある

Rubocop では2種類の raise の書き方をサポートしています。

Exploded - デフォルトの設定

冒頭のエラーはこの設定で発生するもので、例外クラスが複数の引数を取る時にインスタンスを作ることを推奨します。
なので以下のように書きましょう。

# ⭕ 
raise OriginError
raise OriginError, 'これはいかん!!'
raise OriginError.new('これはいかん!!', '@masayuki14')
raise OriginError.new('これはいかん!!', user: '@masayuki14', action: :save)
raise OriginError, 'これはいかん', caller

# ❌
raise OriginError.new
raise OriginError.new('これはいかん!!')

Compact

こちらは引数があれば、例外クラスのインスタンスを作ることを推奨します。

# ⭕ 
raise OriginError
raise OriginError.new('これはいかん!!')
raise OriginError.new('これはいかん!!', '@masayuki14')
raise OriginError.new('これはいかん!!', user: '@masayuki14', action: :save)

# ❌
raise OriginError, 'これはいかん!!'
raise OriginError, 'これはいかん!!', caller

設定ファイルの書き方

.rubocop.yml にはこのように書きます。好みに合わせて設定しましょう。

.rubocop.yml
RaiseArgs:
  EnforcedStyle: exploded
.rubocop.yml
RaiseArgs:
  EnforcedStyle: compact

そもそも raise はKernel Module に定義されたインスタンスメソッド

そもそも raise はメソッドで forif などの制御構文と違って引数を取ることができるので、上記のような書き方ができるわけです。

# ()をつけると急にメソッドに見えてくる
raise(OriginError, 'やっちまったな')
raise(OriginError.new('やっちまったな', user: user, action: :save))

raise() がとる引数についてはこちらでご確認ください。

2
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?