Tatehitoの技術メモ

ソフトウェアエンジニアです。いろいろ書きます。

【Rails】エラー画面が見やすくなるgem『better_errors』を試す

Railsのエラー画面をリッチにするgembetter_errorsを使ってみたので、導入方法を紹介します。

f:id:tatehito-st:20191012205359p:plain
こんな感じでリッチになる。

使用バージョン

  • Ruby 2.6.3
  • Rails 6.0.0
  • better_errors 2.5.1(現行の最新版)
  • binding_of_caller 0.8.0(現行の最新版)

インストールする

Gemfileにbetter_errors'binding_of_caller'を追記してbundle install

開発用なので、development環境のみにインストールします。

# Gemfile

group :development do
  gem 'better_errors', '>= 2.5.1'
  gem 'binding_of_caller', '>= 0.8.0'
end

エラーを発生させてみる

存在しないメソッドを呼ぶことで、意図的にエラーを発生させてみます。ちなみに、Routing Errorではbetter_errorsは動作せず、従来のエラー画面が表示されます。

# pages_controller.rb

class PagesController < ApplicationController
  def index
    local = 100
    @instance = 'hoge'
    sample
  end

  def sample
    undefined
  end
end

pages/indexにアクセスすると、better_errorsのエラー画面が表示されました!

f:id:tatehito-st:20191012205359p:plain

左半分に表示されたスタックトレースを選択すると、その時点での変数の状態などが右側に表示されます。

indexが呼ばれたタイミングでは、ローカル変数localやインスタンス変数@instanceが参照できています。

f:id:tatehito-st:20191012205516p:plain:w500

f:id:tatehito-st:20191012205550p:plain:w300

f:id:tatehito-st:20191012205616p:plain:w300

エラーが発生したタイミングはsample内なので、ローカル変数は定義されていないことがわかります。インスタンス変数@instanceは変わらず参照できていることが分かります。

f:id:tatehito-st:20191012205805p:plain

f:id:tatehito-st:20191012205857p:plain:w300

f:id:tatehito-st:20191012205616p:plain:w300

導入はbundle installするだけでめちゃくちゃ簡単なので、とりあえず入れておくとデバッグが捗るかもしれません!