Rails 4;提出错误并在控制器内捕获

时间:2016-12-01 09:21:56

标签: ruby-on-rails

我喜欢在我的控制器中定义一个rescue_from处理程序来响应错误。

modudle Api
  module V1
    class TreesController < Api::V1::ApiController
      rescue_from TreeNotFound, with: :missing_tree

       def show
         @tree = find_tree
        end

       private

       def missing_tree(error)
         redirect_to(action: :index, flash: error.message)
        end

       def find_tree
         find_forest.trees.find(params[:id])
       rescue ActiveRecord::RecordNotFound
         raise TreeNotFound, "Couldn't find a tree to hug"
       end
     end
   end
end

但是我收到了一些错误Api::V1::TreesController::TreeNotFound

有什么想法吗?

更新

    # api_controller.rb    
    module Api
      module V1
        class ApiController < JSONAPI::ResourceController
          skip_before_action :verify_authenticity_token # Disable CSRF to enable to function as API

          respond_to :json

          # NOTE: This block is used when you put unrelated values
          rescue_from(ArgumentError) do |e|
            render json: { error: e.message }, states: 400 # :bad_request
          end

          rescue_from(ActionController::ParameterMissing) do |e|
            error = {}
            error[e.param] = ['parameter is required']
            response = { errors: [error] }
            render json: response, status: 422 # :unprocessable_entity
          end   
        end
      end
    end

1 个答案:

答案 0 :(得分:1)

you need to declare the error class first before you can use it. Do this by inheriting from StandardError.

class TreeNotFound < StandardError
end