首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails 4 Grape :RoutingError

Rails 4 Grape :RoutingError
EN

Stack Overflow用户
提问于 2014-05-06 05:52:14
回答 1查看 2K关注 0票数 3

我正在尝试用json格式对它的所有动词做出Grape的应答。问题是我不能让它回答json格式的路由错误。我甚至无法拯救ActionController::RoutingError。

我阅读了这个链接https://github.com/intridea/grape/pull/342,并将级联指令设置为false,但是API只在纯文本中回答“找不到”。

代码语言:javascript
复制
$ curl -X GET http://localhost:3000/api/wrong_uri
Not Found

使用详细的选项:

代码语言:javascript
复制
$ 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

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-05-07 15:03:20

通过指定cascade false,您的意思是应该允许Grape处理HTTP错误,而不受Rails的干扰。因此,当在API的挂载点下请求一个不匹配的URI时,不会生成任何ActionController::RoutingError (这应该由Rails完成),而是逐字返回葡萄默认的“非匹配路由”处理程序的输出。有些无济于事的是,即使指定了format :json,这个处理程序也会生成一个简单的"Not“消息,这就是您正在看到的行为。

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

代码语言:javascript
复制
# 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块的正文,以满足您的需要。

出于某种原因,两个块似乎都是捕获所有不可匹配的路由所必需的;这是Grape语法或我的理解的一个限制。

票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23486871

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档