module Concerns
  module ExceptionHandler
    extend ActiveSupport::Concern

    included do
      rescue_from ActionController::RoutingError, with: :render_404
      rescue_from ActionController::UnknownController, with: :render_404
      rescue_from ActiveRecord::RecordNotFound, with: :render_404

      rescue_from Pundit::NotAuthorizedError, with: :auth_error
    end

    def auth_error(exception)
      session[:return_to] = request.env['REQUEST_URI']
      message = exception.message

      if current_user.nil?
        redirect_to new_user_registration_url, alert: I18n.t('devise.failure.unauthenticated')
      elsif request.env["HTTP_REFERER"]
        redirect_to :back, alert: message
      else
        redirect_to root_path, alert: message
      end
    end

    def render_404(exception)
      @not_found_path = exception.message
      respond_to do |format|
        format.html { render template: 'errors/not_found', layout: 'layouts/juntos_bootstrap', status: 404 }
        format.all { render nothing: true, status: 404 }
      end
    end

  end
end

module Concerns
  module ExceptionHandler
    extend ActiveSupport::Concern

    included do
      rescue_from ActionController::RoutingError, with: :render_404
      rescue_from ActionController::UnknownController, with: :render_404
      rescue_from ActiveRecord::RecordNotFound, with: :render_404

      rescue_from Pundit::NotAuthorizedError, with: :auth_error
    end

    def auth_error(exception)
      message = exception.message

      unless ajax_request?
        session[:return_to] = request.env['REQUEST_URI']
      end

      if current_user.nil?
        redirect_to new_user_registration_url, alert: I18n.t('devise.failure.unauthenticated')
      elsif request.env["HTTP_REFERER"]
        redirect_to :back, alert: message
      else
        redirect_to root_path, alert: message
      end
    end

    def render_404(exception)
      @not_found_path = exception.message
      respond_to do |format|
        format.html { render template: 'errors/not_found', layout: 'layouts/juntos_bootstrap', status: 404 }
        format.all { render nothing: true, status: 404 }
      end
    end

  end
end

Add ajax_request verification to Pundit gem exception handler
Add ajax_request verification to Pundit gem exception handler

Verification to ajax requests to avoid the update of session[:return_to] on these cases.
