【问题标题】:Rails 4.2 ActionController:BadRequest custom error messageRails 4.2 ActionController:BadRequest 自定义错误信息
【发布时间】:2016-08-30 13:59:55
【问题描述】:

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

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 异常添加自定义消息?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 actioncontroller


    【解决方案1】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2015-12-22
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 2017-01-28
      • 2021-02-10
      相关资源
      最近更新 更多