加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails 4.2 ActionController:BadRequest自定

发布时间:2020-12-17 02:49:29 所属栏目:百科 来源:网络整理
导读:我想从我的控制器返回,如果验证失败或缺少参数400 – 错误的请求.所以在我的控制器中如果有 if params["patch"].nil? then raise ActionController::BadRequest.new( "The Json body needs to be wrapped inside a "Patch" key")end 我在我的应用程序控制
我想从我的控制器返回,如果验证失败或缺少参数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”}而不是我提供的哈希.

在控制台中,我得到了相同的行为.举起ActiveRecord :: RecordNotFound,“foo”确实引发了ActiveRecord :: RecordNotFound:foo.

但是提出ActionController :: BadRequest,“baa”会导致

ActionController :: BadRequest:ActionController :: BadRequest

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

解决方法

试试这个:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读