0

默認情況下,Rails爲404 Resource Not Found500 Internal Server Error提供有用的HTML頁面。但是對於我的JSON API,我想提供JSON格式的回覆。針對JSON請求的Rails 3默認異常+ 404處理

如何爲JSON請求設置默認的異常處理?在routes.rb

NOT_FOUND_EXC = [ActionController::RoutingError, 
       AbstractController::ActionNotFound, 
       ActiveRecord::RecordNotFound] 

class BaseapiController < ActionController::Base 
    respond_to :json 
    rescue_from StandardError, with: :show_json_error 

    def resource_not_found 
    url = request.fullpath 
    respond_with(url), status: :not_found) 
    end 

    private 

    def show_json_errors(exc) 
    case exc 
     when *NOT_FOUND_EXC 
     return resource_not_found 
     else 
     logger.error exc.message 
     logger.error exc.backtrace.join("\n") 
     respond_with(exc), status: :internal_server_error) 
    end 
    end 
end 

而且我已經定義是::

回答

0

我添加了一個基本的控制器對所有API控制器

namespace :api do 
    ... 
end 
match 'api/*url', to: 'baseapi#resource_not_found' 

現在rescue_from條款捕獲所有異常和未匹配的路由是通過#resource_not_found捕獲。

我認爲這會忽略Rails異常處理的一些基礎知識,因爲通常應該在開發中處理具有表達細節的錯誤,並在產品中進行簡單呈現。我顯然不是這樣做的。而且HTML異常仍然可以通過。所以歡迎提供反饋和替代方案,我是Rails的新手,希望我錯過了一個可以接入的機制。