9

Tôi đã đoạn mã sau:rescue_from :: AbstractController :: ActionNotFound không làm việc

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 

Họ tất cả công việc hoàn hảo, ngoại trừ :: AbstractController :: ActionNotFound

Tôi cũng cố gắng

AbstractController::ActionNotFound 
ActionController::UnknownAction 

lỗi:

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

Trả lời

7

This similar question cho thấy rằng bạn không còn có thể bắt được ngoại lệ ActionNotFound. Kiểm tra liên kết để biết cách giải quyết. This suggestion để sử dụng phần mềm trung gian Rack để bắt các 404 trông sạch sẽ nhất với tôi.

3

Để cứu AbstractController::ActionNotFound trong một bộ điều khiển, bạn có thể thử một cái gì đó như thế này:

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 

này ghi đè phương pháp process của AbstractController::Base làm tăng AbstractController::ActionNotFound (xem source).

0

Tôi nghĩ chúng ta nên bắt AbstractController::ActionNotFound trong ApplicationController. Tôi đã thử sau rằng dường như không hoạt động.

rescue_from ActionController::ActionNotFound, with: :action_not_found 

Tôi đã tìm thấy nhiều cách rõ ràng hơn để xử lý ngoại lệ này trong ApplicationController. Để xử lý ActionNotFound Ngoại lệ trong ứng dụng của bạn, bạn phải ghi đè phương thức action_missing trong bộ điều khiển ứng dụng của mình.

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

Solution Phỏng theo: coderwall handling exceptions in your rails application

0

Trọng process, như mô tả của Grégoire trong câu trả lời của mình, dường như làm việc. Tuy nhiên, mã Rails nói thay vì ghi đè process_action. Tuy nhiên, điều đó không có tác dụng vì process_action không bao giờ được gọi do kiểm tra action_name trong số process.

https://github.com/rails/rails/blob/v3.2.21/actionpack/lib/abstract_controller/base.rb#L115

https://github.com/rails/rails/blob/v3.2.21/actionpack/lib/abstract_controller/base.rb#L161