首页 > 解决方案 > 在 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.

标签: ruby-on-railsjsonerror-handlingroutesrails-api

解决方案


如果您想为所有未定义的路由呈现相同的响应,您可以执行以下操作,

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将呈现我们的自定义响应的方法。


推荐阅读