简体   繁体   English

如何在Rails API中处理错误的请求/错误的参数?

[英]How to handle bad requests / wrong parameters in a rails api?

For example, an api consumer sends: 例如,一个api使用者发送:

"ticket": [{ "param": "value"}]

The controller does: 控制器执行以下操作:

params.require(:ticket).permit(:name)

This would return a 500 error: "Undefined method permit for array" 这将返回500错误:“数组的未定义方法许可”

Is there a DRY / best practice way to handle this? 是否有DRY /最佳做法来处理此问题? I think a status 400 should be returned instead. 我认为应该返回状态400

I think the strong parameters gem should handle this internally, but they don't, so here is my solution 我认为强参数gem应该在内部处理此问题,但它们不能,所以这是我的解决方案

  rescue_from NoMethodError do |exception|
    if exception.message =~ /undefined method `permit' for/
      render_error(message: 'Invalid parameter format.', type: :invalid_parameters, status: :bad_request)
    else
      raise
    end
  end

Based on your solution .. you would want to handle all the possibilities verse a specific error response. 根据您的解决方案..您可能希望通过特定的错误响应来处理所有可能性。 You can set in a rescue in your render method like this and set unauthorized if there is a method error or just something else going wrong : 您可以像这样在渲染方法中进行营救,并在出现方法错误或其他错误的情况下设置未经授权的内容:

begin
  render json: json, status: 200 
rescue_from NoMethodError do |exception|
  render :unauthorized
end
rescue => e
  render :unauthorized
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM