🌟

Rails6の学習・エラーページその1

2022/11/07に公開

rescue_from

Railsのコントローラーには rescue_from というクラスメソッドが用意されている。アクション内で発生した例外処理を簡単に指定できる。

rescue_from Forbidden, with: :rescue403

rescue403 はコントローラーのプライベードメソッド

  def rescue403(e)
    @exception = e
    render "errors/forbidden", status: 403
  end

引数から受け取ったエラーをテンプレート errors/forbidden で利用できるようにしている。

500 Internal Server Error

productionモードをローカルで起動する方法のメモ。productionモードではソースコードを変更しても、アプリケーションを再起動するまで反映されない。これだと開発しにくいので設定を変更する。

config/environments/production.rb

config.cache_classes = false

productionモードでサーバーを起動。

$ bin/rails s -e production -b 0.0.0.0

productionモードでログを見るにはDockerの外でtailコマンドを使う。

% tail -f apps/baukis2/log/production.log

例外の補足

app/contollers/application_controller.rb

class ApplicationController < ActionController::Base
  layout :set_layout

  class Forbidden < ActionController::ActionControllerError; end
  class IpAddressRejected < ActionController::ActionControllerError; end

  rescue_from StandardError, with: :rescue500
  rescue_from Forbidden, with: :rescue403
  rescue_from IpAddressRejected, with: :rescue403

  private

  def set_layout
    if params[:controller].match(%r{\A(staff|admin|customer)/})
      Regexp.last_match[1]
    else
      "customer"
    end
  end

  def rescue403(e)
    @exception = e
    render "errors/forbidden", status: 403
  end

  def rescue500(e)
    render "errors/internal_server_error", status: 500
  end
end
  • Forbidden クラスと IpAddressRejected クラスは StandardError を継承するクラス。必ず StandardError の後に rescue_from を実行すること。
  • ApplicationControllerで定義して、実際に各コントローラーで例外処理を実行する場合は、raise Forbidden raise IpAddressRejected とする。

ERBテンプレートでの利用

<div id="error">
  <h1>403 Forbidden</h1>
  <p>
    <%=
      case @exception
      when ApplicationController::IpAddressRejected
        "あなたのIPアドレス(#{request.ip})からは利用できません。"
      else
        "指定されたページを閲覧する権限がありません"
      end
    %>
  </p>
</div>

コントローラー外で定義した例外を利用したい場合は名前空間から指定する。ApplicationController::IpAddressRejected

Discussion

ログインするとコメントできます