Rails 5 way to handle ActionController::ParameterMissing

眉间皱痕 提交于 2020-03-05 04:58:08

问题


If a parameter that's required is missing using strong parameters, the Rails server will respond with an HTTP 500.

This does not give me control over giving the user feedback with what exactly went wrong. Does it not make sense to be able to send them back a message such a required parameter is missing?

What is the "Rails way" of giving appropriate user feedback on ActionController::ParameterMissing? Is one supposed to capture the exception and handle your request response there? It seems wrong to do that in every controller.


回答1:


You can use

rescue_from ActionController::ParameterMissing do |e|
  render 'something'
end

in your ApplicationController (or whatever your parent controller is).

As to whether you should inform users or not, I think it depends on what your controllers are doing. If they are API controllers, it definitely makes sense to handle that gracefully, as the users are responsible for preparing the input. If they are accepting data from your HTML forms it's, in my opinion, not that important as the missing parameters probably mean that the user tinkered with the HTML, or something went really wrong inside the browser.



来源:https://stackoverflow.com/questions/52543840/rails-5-way-to-handle-actioncontrollerparametermissing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!