我有一个普通的HTML前端和一个JSON API在我的Rails应用程序中。现在,如果有人调用/api/not_existent_method.json
,它将返回默认的HTML404页面。有没有办法将其更改为类似于{"error": "not_found"}
的内容,同时保持原始的404页面不变?
发布于 2012-04-21 16:37:08
一位朋友向我推荐了一个优雅的解决方案,它不仅可以处理404个错误,还可以处理500个错误。事实上,它会处理所有错误。关键是,每个错误都会生成一个异常,该异常会通过机架中间件堆栈向上传播,直到被其中一个中间件处理。如果你有兴趣了解更多,你可以看this excellent screencast。Rails有自己的异常处理程序,但您可以使用文档较少的exceptions_app
配置选项来覆盖它们。现在,您可以编写自己的中间件,也可以将错误路由回rails,如下所示:
# In your config/application.rb
config.exceptions_app = self.routes
然后,您只需在config/routes.rb
中匹配这些路由
get "/404" => "errors#not_found"
get "/500" => "errors#exception"
然后您只需创建一个控制器来处理此问题。
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
文件中禁用回溯功能。
config.consider_all_requests_local = false
发布于 2014-06-27 19:53:26
我喜欢创建一个单独的API控制器来设置格式(json)和特定于api的方法:
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测试:
it 'should return 404' do
get "/api/route/specific/to/your/app/", format: :json
expect(response.status).to eq(404)
end
https://stackoverflow.com/questions/10253366
复制相似问题