首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >需要在Rails中返回JSON格式的404错误

需要在Rails中返回JSON格式的404错误
EN

Stack Overflow用户
提问于 2012-04-21 04:49:43
回答 2查看 48.3K关注 0票数 79

我有一个普通的HTML前端和一个JSON API在我的Rails应用程序中。现在,如果有人调用/api/not_existent_method.json,它将返回默认的HTML404页面。有没有办法将其更改为类似于{"error": "not_found"}的内容,同时保持原始的404页面不变?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-21 16:37:08

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

代码语言:javascript
复制
# In your config/application.rb
config.exceptions_app = self.routes

然后,您只需在config/routes.rb中匹配这些路由

代码语言:javascript
复制
get "/404" => "errors#not_found"
get "/500" => "errors#exception"

然后您只需创建一个控制器来处理此问题。

代码语言:javascript
复制
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文件中禁用回溯功能。

代码语言:javascript
复制
config.consider_all_requests_local = false
票数 117
EN

Stack Overflow用户

发布于 2014-06-27 19:53:26

我喜欢创建一个单独的API控制器来设置格式(json)和特定于api的方法:

代码语言:javascript
复制
class ApiController < ApplicationController
  respond_to :json

  rescue_from ActiveRecord::RecordNotFound, with: :not_found
  # Use Mongoid::Errors::DocumentNotFound with mongoid

  def not_found
    respond_with '{"error": "not_found"}', status: :not_found
  end
end

RSpec测试:

代码语言:javascript
复制
  it 'should return 404' do
    get "/api/route/specific/to/your/app/", format: :json
    expect(response.status).to eq(404)
  end
票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10253366

复制
相关文章

相似问题

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