9

我有以下代碼:rescue_from ::一個AbstractController :: ActionNotFound不工作

unless Rails.application.config.consider_all_requests_local 
    rescue_from Exception, with: :render_exception 
    rescue_from ActiveRecord::RecordNotFound, with: :render_exception 
    rescue_from ActionController::UnknownController, with: :render_exception 
    rescue_from ::AbstractController::ActionNotFound, with: :render_exception 
    rescue_from ActiveRecord::ActiveRecordError, with: :render_exception 
    rescue_from NoMethodError, with: :render_exception 
end 

他們所有的工作完美無瑕,除了::一個AbstractController :: ActionNotFound

我也試過

AbstractController::ActionNotFound 
ActionController::UnknownAction 

錯誤:

AbstractController::ActionNotFound (The action 'show' could not be found for ProductsController): 

回答

7

This similar question表明您不能再捕獲ActionNotFound異常。檢查鏈接的解決方法。 This suggestion使用Rack中間件來捕捉404s對我來說看起來最清潔。

3

要在控制器搶救AbstractController::ActionNotFound,你可以嘗試這樣的事:

class UsersController < ApplicationController 

    private 

    def process(action, *args) 
    super 
    rescue AbstractController::ActionNotFound 
    respond_to do |format| 
     format.html { render :404, status: :not_found } 
     format.all { render nothing: true, status: :not_found } 
    end 
    end 


    public 

    # actions must not be private 

end 

這將覆蓋的AbstractController::Baseprocess方法提高AbstractController::ActionNotFound(見source)。

0

我想我們應該趕上AbstractController::ActionNotFoundApplicationController。我試過以下似乎不工作

rescue_from ActionController::ActionNotFound, with: :action_not_found 

我發現在ApplicationController中處理此異常的方法更加簡潔。要處理應用程序中的ActionNotFound異常,您必須覆蓋應用程序控制器中的action_missing方法。

def action_missing(m, *args, &block) 
    Rails.logger.error(m) 
    redirect_to not_found_path # update your application 404 path here 
end 

解決方案摘自:coderwall handling exceptions in your rails application

相關問題