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

10
我希望你的控制器能够在验证失败或参数缺失时返回400 - 错误请求。因此,在我的控制器中,我有以下代码:
if params["patch"].nil? then
  raise ActionController::BadRequest.new( "The Json body needs to be wrapped inside a \"Patch\" key")
end

我在应用程序控制器中用以下代码捕获了这个错误:

rescue_from ActionController::BadRequest, with: :bad_request


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

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

在控制台中,我得到了相同的行为。实际上,raise ActiveRecord::RecordNotFound, "foo"会引发ActiveRecord::RecordNotFound: foo异常。

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

ActionController::BadRequest: ActionController::BadRequest

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

1个回答

18

试一下这个:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接