【问题标题】:Grape custom error with status code带有状态码的葡萄自定义错误
【发布时间】:2015-06-16 11:42:58
【问题描述】:

您好,我现在正在使用 Grape 进行 Rails 项目 基本上我想用葡萄做一个自定义错误,因为它支持。 我已经设法创建了自定义错误,就像这样

module API
  module ErrorFormatter
    def self.call(message, backtrace, options, env)
      { :response_type => 'error', :details => message }.to_json
    end
  end
end

它工作正常,但是如果我想在上面添加更多细节怎么办,比如我们葡萄发送的状态码/我们手动传递方法error!,所以它会在 json 上有状态码。

可能是这样的

{ :status_code: *status_code_here*, :response_type => 'error', :details => message }

我如何设置 status_code_here 的值

已编辑

这是葡萄的基础/根目录

  class Base < Grape::API
    format :json
    error_formatter :json, API::ErrorFormatter

    mount API::V1::Base
  end

所以这意味着我现在使用的是自定义错误而不是葡萄的预定义错误。 据我所知,此自定义错误将以两种方式调用:

  1. Grape 在你发送一个缺失的参数时自动使用这个 您将参数设置为 requires 的 API
  2. 当您显式调用error!() 方法时,就像https://github.com/intridea/grape#raising-exceptions

有什么帮助吗?

谢谢

【问题讨论】:

    标签: ruby-on-rails grape grape-api


    【解决方案1】:

    状态码嵌入在机架环境中。
    您可以通过以下方式获得它:

    env['api.endpoint'].status

    所以你的方法的主体是:

    { :status_code: env['api.endpoint'].status, :response_type => 'error', :details => message }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-19
      • 2011-11-02
      • 2014-12-06
      • 2015-06-13
      • 2016-05-11
      • 1970-01-01
      相关资源
      最近更新 更多