3

我正在尝试让葡萄 API 以 json 格式回答其所有动词。问题是我无法回答 json 格式的路由错误。我什至无法挽救 ActionController::RoutingError。

我已阅读此链接https://github.com/intridea/grape/pull/342并将级联指令设置为 false,但 API 仅以纯文本形式回答“未找到”。

$ curl -X GET http://localhost:3000/api/wrong_uri
Not Found

带有详细选项:

$ curl -X GET http://localhost:3000/api/wrong_uri -v
* About to connect() to localhost port 3000 (#0)
*   Trying 127.0.0.1... connected
> GET /api/wrong_uri HTTP/1.1
> User-Agent: curl/7.22.0 (i686-pc-linux-gnu) libcurl/7.22.0 OpenSSL/1.0.1 zlib/1.2.3.4 libidn/1.23 librtmp/2.3
> Host: localhost:3000
> Accept: */*
> 
< HTTP/1.1 404 Not Found 
< Content-Type: text/html
< Cache-Control: no-cache
< X-Request-Id: 3cc74a78-3295-4c1f-b989-66d6fac50e5c
< X-Runtime: 0.002980
< Server: WEBrick/1.3.1 (Ruby/2.1.1/2014-02-24)
< Date: Tue, 06 May 2014 05:46:33 GMT
< Content-Length: 9
< Connection: Keep-Alive
< 
* Connection #0 to host localhost left intact
* Closing connection #0
Not Found

我的葡萄文件 /app/api/api.rb

module API
  class Base < Grape::API
    format :json
    default_error_formatter :json
    cascade false

    rescue_from CanCan::AccessDenied do |e|
      Rack::Response.new({ error: "Forbidden", detail: "Access denied", status: '403' }.to_json, 403).finish
    end

    # it doesn't catch ActionController::RoutingError
    # rescue_from :all do |e|
    #   error_response({ message: "rescued from #{e.class.name}" })
    # end

    helpers ApiHelpers

    mount API::Auth
    mount API::V2
    mount API::V1
  end
end
4

1 回答 1

8

通过指定cascade false你说应该允许葡萄处理 HTTP 错误而不受 Rails 的干扰。因此,当请求 API 挂载点下的不匹配 URI 时,ActionController::RoutingError会生成 no(这将由Rails 完成),而是逐字返回 Grape 的默认“不匹配路由”处理程序的输出。有点无益的是,即使format :json已指定,此处理程序也会生成一个普通的“未找到”消息,这就是您所看到的行为。

V1解决方案是提供您自己的匹配器来捕获您和V2模块中指定的路线以外的路线。尝试将此代码添加到三个语句的API::Base 下方:mount

# Generate a properly formatted 404 error for all unmatched routes except '/'
route :any, '*path' do
  error!({ error:  'Not Found',
           detail: "No such route '#{request.path}'",
           status: '404' },
         404)
end

# Generate a properly formatted 404 error for '/'
route :any do
  error!({ error:  'Not Found',
           detail: "No such route '#{request.path}'",
           status: '404' },
         404)
end

当然,您会想要编辑每个route块的主体以满足您的需要。

出于某种原因,这两个区块似乎对于捕获所有不匹配的路线都是必要的;这是葡萄匹配器语法或我理解的限制。

于 2014-05-07T15:03:20.417 回答