Rails 4添加了一个异常 ActionDispatch :: ParamsParser :: ParseError 异常,但由于它在中间件堆栈中,它似乎无法在普通控制器环境中获救。在json API应用程序中,我想用标准错误格式进行响应。
此gist显示了插入中间件以拦截和响应的策略。按照这种模式,我有:
application.rb中:
module Traphos
class Application < Rails::Application
....
config.middleware.insert_before ActionDispatch::ParamsParser, "JSONParseError"
end
end
中间件是:
class JSONParseError
def initialize(app)
@app = app
end
def call(env)
begin
@app.call(env)
rescue ActionDispatch::ParamsParser::ParseError => e
[422, {}, ['Parse Error']]
end
end
end
如果我在没有中间件的情况下运行测试,我会得到(规范):
Failures:
1) Photo update attributes with non-parseable json
Failure/Error: patch update_url, {:description => description}, "CONTENT_TYPE" => content_type, "HTTP_ACCEPT" => accepts, "HTTP_AUTHORIZATION" => @auth
ActionDispatch::ParamsParser::ParseError:
399: unexpected token at 'description=Test+New+Description]'
这正是我所期望的(ParseError,我无法rescue_from)。
现在只需要在上面的中间件中添加更改:
2) Photo update attributes with non-parseable json
Failure/Error: response.status.should eql(422)
expected: 422
got: 200
并且日志显示正在执行标准控制器操作并返回正常响应(尽管因为它没有接收任何参数而没有更新任何内容)。
我的问题:
如何从ParseError中解救并返回自定义响应。感觉就像我在正确的轨道上,但不是那里。
我无法理解为什么,在引发和获救异常时,控制器操作仍然继续进行。
非常感谢, - Kip
答案 0 :(得分:7)
事实证明,可以使用例外应用程序配置中间件堆栈, ActionDispatch :: ShowExceptions 。
module Traphos
class Application < Rails::Application
# For the exceptions app
require "#{config.root}/lib/exceptions/public_exceptions"
config.exceptions_app = Traphos::PublicExceptions.new(Rails.public_path)
end
end
很大程度上依赖于我现在使用的Rails:
module Traphos
class PublicExceptions
attr_accessor :public_path
def initialize(public_path)
@public_path = public_path
end
def call(env)
exception = env["action_dispatch.exception"]
status = code_from_exception(env["PATH_INFO"][1..-1], exception)
request = ActionDispatch::Request.new(env)
content_type = request.formats.first
body = {:status => { :code => status, :exception => exception.class.name, :message => exception.message }}
render(status, content_type, body)
end
private
def render(status, content_type, body)
format = content_type && "to_#{content_type.to_sym}"
if format && body.respond_to?(format)
render_format(status, content_type, body.public_send(format))
else
render_html(status)
end
end
def render_format(status, content_type, body)
[status, {'Content-Type' => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}",
'Content-Length' => body.bytesize.to_s}, [body]]
end
def render_html(status)
found = false
path = "#{public_path}/#{status}.#{I18n.locale}.html" if I18n.locale
path = "#{public_path}/#{status}.html" unless path && (found = File.exist?(path))
if found || File.exist?(path)
render_format(status, 'text/html', File.read(path))
else
[404, { "X-Cascade" => "pass" }, []]
end
end
def code_from_exception(status, exception)
case exception
when ActionDispatch::ParamsParser::ParseError
"422"
else
status
end
end
end
end
要在测试环境中使用它,需要设置配置变量(否则您将在开发和测试中获得标准异常处理)。所以要测试我(编辑只是关键部分):
describe Photo, :type => :api do
context 'update' do
it 'attributes with non-parseable json' do
Rails.application.config.consider_all_requests_local = false
Rails.application.config.action_dispatch.show_exceptions = true
patch update_url, {:description => description}
response.status.should eql(422)
result = JSON.parse(response.body)
result['status']['exception'].should match(/ParseError/)
Rails.application.config.consider_all_requests_local = true
Rails.application.config.action_dispatch.show_exceptions = false
end
end
end
它以公共API的方式执行,并且可以适应我可能选择自定义的任何其他异常。
答案 1 :(得分:1)
本文(也是2013年)thoughtbot也涵盖了此主题。只有在您请求json
时,他们才会将响应放在此中间件服务中if env['HTTP_ACCEPT'] =~ /application\/json/
error_output = "There was a problem in the JSON you submitted: #{error}"
return [
400, { "Content-Type" => "application/json" },
[ { status: 400, error: error_output }.to_json ]
]
else
raise error
end