需要在 Rails 中返回 JSON 格式的 404 错误 [英] Need to return JSON-formatted 404 error in Rails

查看:56
本文介绍了需要在 Rails 中返回 JSON 格式的 404 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 Rails 应用程序中有一个普通的 HTML 前端和一个 JSON API.现在,如果有人调用 /api/not_existent_method.json 它将返回默认的 HTML 404 页面.有什么方法可以将其更改为 {"error": "not_found"} 之类的内容,同时保持 HTML 前端的原始 404 页面完好无损?

I am having a normal HTML frontend and a JSON API in my Rails App. Now, if someone calls /api/not_existent_method.json it returns the default HTML 404 page. Is there any way to change this to something like {"error": "not_found"} while leaving the original 404 page for the HTML frontend intact?

推荐答案

一位朋友向我指出了一个优雅的解决方案,它不仅可以处理 404 错误,还可以处理 500 错误.事实上,它处理每一个错误.关键是,每个错误都会生成一个异常,该异常通过机架中间件堆栈向上传播,直到被其中一个处理.如果您有兴趣了解更多信息,可以观看这个精彩的截屏视频.Rails 有自己的异常处理程序,但您可以通过文档较少的 exceptions_app 配置选项覆盖它们.现在,您可以编写自己的中间件,也可以将错误路由回 Rails,如下所示:

A friend pointed me towards a elegant solution that does not only handle 404 but also 500 errors. In fact, it handles every error. The key is, that every error generates an exception that propagates upwards through the stack of rack middlewares until it is handled by one of them. If you are interested in learning more, you can watch this excellent screencast. Rails has it own handlers for exceptions, but you can override them by the less documented exceptions_app config option. Now, you can write your own middleware or you can route the error back into rails, like this:

# In your config/application.rb
config.exceptions_app = self.routes

然后你只需要在你的 config/routes.rb 中匹配这些路由:

Then you just have to match these routes in your config/routes.rb:

get "/404" => "errors#not_found"
get "/500" => "errors#exception"

然后你只需创建一个控制器来处理这个问题.

And then you just create a controller for handling this.

class ErrorsController < ActionController::Base
  def not_found
    if env["REQUEST_PATH"] =~ /^\/api/
      render :json => {:error => "not-found"}.to_json, :status => 404
    else
      render :text => "404 Not found", :status => 404 # You can render your own template here
    end
  end

  def exception
    if env["REQUEST_PATH"] =~ /^\/api/
      render :json => {:error => "internal-server-error"}.to_json, :status => 500
    else
      render :text => "500 Internal Server Error", :status => 500 # You can render your own template here
    end
  end
end

最后要补充的一点:在开发环境中,rails 通常不渲染 404 或 500 页,而是打印回溯.如果您想在开发模式下查看 ErrorsController 的运行情况,请禁用 config/enviroments/development.rb 文件中的回溯内容.

One last thing to add: In the development environment, rails usally does not render the 404 or 500 pages but prints a backtrace instead. If you want to see your ErrorsController in action in development mode, then disable the backtrace stuff in your config/enviroments/development.rb file.

config.consider_all_requests_local = false

这篇关于需要在 Rails 中返回 JSON 格式的 404 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆