【问题标题】:Using RABL for error handling in Rails json在 Rails json 中使用 RABL 进行错误处理
【发布时间】:2013-06-27 01:26:22
【问题描述】:

我正在使用 Rails 和 RABL 创建一个 json api。

有没有办法使用 RABL 显示自定义错误消息?

例如,这个想法是在找不到对象而不是标准模板时将错误消息显示为json,例如它显示消息:

{"errors":"Foo that you were looking for could not be found."}

例如,我尝试使用以下代码在 API 中显示自定义错误消息:

class Api::V1::FooController < ApplicationController
respond_to :json
before_filter :find_foo, :only =>[:show]

    def find_foo
         @foo = Foo.find(params[:id])
         rescue ActiveRecord::RecordNotFound
            @errors = { :errors => "Foo that you were looking for could not be found."}
            respond_with(errors.to_json, :status => 404)
    end

    def show
        respond_with(@foo)
    end
end

在我的 Show RABL 模板中:

object @foo

attributes :id, :name

node :errors do |o|
    o.errors
end

这样做我收到的是 RABL 模板的错误消息,而不是正确的 json:

undefined method `errors' for nil:NilClass

【问题讨论】:

    标签: ruby-on-rails ruby json rabl


    【解决方案1】:

    对于您的错误状态,您应该使用render 而不是respond_with

    render(:json => errors.to_json, :status => 404)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-04
      • 2018-05-04
      • 2011-09-18
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      相关资源
      最近更新 更多