ruby-on-rails - 在 Rails API 服务中访问未定义的路由时呈现 JSON 格式的响应
问题描述
情况如下:
如果用户尝试使用未定义的路由访问我的 rails-api 服务,rails 将捕获异常并将 html 呈现Routing Error:
给浏览器。
但是我希望我的 rails-api 服务执行的是它可以捕获任何这样的错误并将json-formatted
错误信息返回到请求源,如下所示:
# if i visit a route which is undefined in my config/routes.rb like this:
HTTP.get('http://localhost:3000/api/v1/route/of/undefined')
# what i want it to render to the page is:
{status: 404, err_msg: 'route of undefined, please check again.'}
在我采取行动之前,我发现 Rails 在初始化控制器之前将请求与路由匹配,因此如果我添加rescue_from
到我的ApplicationController
,ApplicationController 没有机会挽救异常。
另外,我在我的项目中添加了以下行:
# config/application.rb
config.exceptions_app = self.routes
# config/environments/development.rb
config.consider_all_requests_local = false
接下来我该怎么办?我搜索了很多,但找不到解决这个问题的答案。尤其是在一个rails api service
.
解决方案
如果您想为所有未定义的路由呈现相同的响应,您可以执行以下操作,
match '*path', to: "error_controller#handle_root_not_found", via: [:get, :post]
将此行添加到 route.rb 的末尾。之后生成error_controller
并定义handle_root_not_found
方法,它将呈现您的自定义响应。
def handle_root_not_found
render json: { message: "route not found"}, status: 404
end
所以在这种情况下会发生什么,当你请求一个特定的路由时,它会以从上到下的方式扫描路由文件。如果找到该路线,那么它会将您重定向到该路线。如果直到该行未找到路由,match '*path'
则此行会将其重定向到handle_root_not_found
将呈现我们的自定义响应的方法。
推荐阅读
- amazon-web-services - AWS GovCloud 中 Cognito 的替代方案
- azure - 企业必应地图 - URL 引荐来源网址
- css - 如何在 Safari 和 Chrome 中类似地呈现按钮?
- xquery - 布尔值在 xquery 中不可赋值
- python - 如何在不创建新会话的情况下配置“requests.get(url)”调用并重试?
- node.js - 为单个对象创建/添加生命周期配置
- c++ - 这是创建控制台应用程序的正确方法吗?
- php - Laravel:更新用户最旧的令牌
- use-case - 工厂模式的小而现实的用例?
- laravel - 有没有一种方法可以在不使用 eloquent 循环的情况下获取 laravel 中第三级孩子的所有数据?