Rails 4.2 ActionController:BadRequest自定义错误消息

the*_*ter 7 ruby ruby-on-rails actioncontroller ruby-on-rails-4

如果验证失败或缺少参数,我想从我的控制器返回400 - bad request.所以在我的控制器中如果有

if params["patch"].nil? then
  raise ActionController::BadRequest.new( "The Json body needs to be wrapped inside a \"Patch\" key")
end
Run Code Online (Sandbox Code Playgroud)

我在我的应用程序控制器中捕获此错误:

rescue_from ActionController::BadRequest, with: :bad_request


def bad_request(exception)
  render status: 400, json: {:error => exception.message}.to_json
end
Run Code Online (Sandbox Code Playgroud)

但似乎我无法在提升时添加自定义消息ActionController::BadRequest.因为当传递无效的主体时,响应仅是,{"error":"ActionController::BadRequest"}而不是我提供的哈希.

在控制台中,我得到了相同的行为. raise ActiveRecord::RecordNotFound, "foo" 确实提高了ActiveRecord::RecordNotFound: foo.

raise ActionController::BadRequest, "baa" 结果是

ActionController::BadRequest: ActionController::BadRequest

如何向BadRequest异常添加自定义消息?

Jon*_*nas 12

试试这个:

raise ActionController::BadRequest.new(), "The Json body needs to be wrapped inside a \"Patch\" key"
Run Code Online (Sandbox Code Playgroud)