Rails | Handle common controller exceptions
mouse 491 · person cloud · link
Last update
2017-06-30
2017
06-30
«rescue controller exceptions»

Here is an example that shows how to deal with the common ActionController::InvalidAuthenticityToken error:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  protect_from_forgery with: :exception

  # http://stackoverflow.com/questions/32133648/rails-test-against-and-handle-actioncontrollerinvalidauthenticitytoken/32135194#32135194
  rescue_from ActionController::InvalidAuthenticityToken,
    with: :rescue_from_invalid_authenticity_token

  protected

  def rescue_from_invalid_authenticity_token(exception)
    render layout: true, text: 'document expired'
  end
end