【问题标题】:Rails 4: Using an exception handler module in API controllerRails 4:在 API 控制器中使用异常处理程序模块
【发布时间】:2018-01-18 03:08:22
【问题描述】:

我试图在我的控制器中使用异常处理程序,但它似乎没有做任何事情:

class API::PaymentsController < ApplicationController
    before_filter :set_client

    def index
        @foo = @client.foo
    end

    ...

    def set_client

      rescue ActiveRecord::RecordNotFound do |e|
        render json: e.message, status: :not_found
      end

      @client = Client.find(params[:client_id])
    end
end

当我转到localhost:3000/clients/[invalid_id]/payments 时,我仍然看到错误:

ActiveRecord::RecordNotFound(找不到 'id'=1 的客户端):
app/controllers/payments_controller.rb:58:in `set_client'

当我期望 RecordNotFound 处理程序来处理这个异常时。我错过了什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 exception-handling


    【解决方案1】:

    救援块在失败之后出现。

    def set_client
      @client = Client.find(params[:client_id])
    rescue ActiveRecord::RecordNotFound => err
      render json: { message: err.message}, status: :not_found
    end
    

    【讨论】:

    • 非常感谢。救援后我还加了一个不必要的end
    猜你喜欢
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 2022-07-07
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 2018-03-30
    • 2018-12-05
    相关资源
    最近更新 更多