Rails 4添加了一个异常ActionDispatch :: ParamsParser :: ParseError异常,但由于它在中间件堆栈中,它似乎无法在普通控制器环境中获救.在json API应用程序中,我想用标准错误格式进行响应.
这个要点显示了插入中间件以拦截和响应的策略.遵循这种模式我有:
application.rb中:
module Traphos
class Application < Rails::Application
....
config.middleware.insert_before ActionDispatch::ParamsParser, "JSONParseError"
end
end
Run Code Online (Sandbox Code Playgroud)
中间件是:
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
Run Code Online (Sandbox Code Playgroud)
如果我在没有中间件的情况下运行测试,我会得到(spec):
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]'
Run Code Online (Sandbox Code Playgroud)
这正是我所期望的(ParseError,我无法rescue_from). …