7
1

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 1 year has passed since last update.

[Ruby ensure句]エラーが起きてもユーザーには知らせない。でもシステム管理者には知らせたい。

Posted at

はじめに

業務の中で、「この処理の途中で落ちた時には、ユーザーにはエラー画面を出さずにシステム側でエラー内容を認識できる状態にとどめたいよね〜」という状況に直面しました。この要望を満たすために使用した、Rubyのensure句についてまとめたいと思います。

Rubyのensure句とは

はじめに、ensure句とはなんぞやというところからスタートです。
ensureはbegin...rescue...ensureの構造の中で使用され、公式リファレンスには以下のように解説されています。

ensure 節が存在する時は begin 式を終了する直前に必ず ensure 節の本体を評価します。

つまり、例外が発生するしないに関係なくこの処理を行うよ〜 ってのが実現できるわけです。

実装例

今回の例では、データの保存に失敗した際に、システム管理者にエラーメールを送信し、ユーザーにはエラー画面を出さずに処理を終えるというシナリオを想定します。

  def save_log_data(log_data)
    log_data.status = 'COMPLETED'
    log_data.save!
  rescue ActiveRecord::RecordInvalid => e
    send_error_email(e)
  ensure
    render status: :ok
  end

上記の例では、データ保存中に例外が発生した場合、rescue句でエラーメールが送信されます。ensure句では、例外の有無に関わらず正常なステータスが返却されます。

まとめ

このようにensure句は非常に便利ですが、その特性から 処理の失敗を隠蔽できてしまう というリスクもあります。重大なエラーを見過ごすことがないよう、適切なエラーハンドリングを行うことが重要です。

参考元

7
1
0

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?