Rails中使用Grape如何捕获接口未定义的非法请求参数
Grape 未声明参数校验实现方案
完全可以通过Grape内置的严格参数校验功能实现需求,无需额外在模型层编写校验逻辑,可通过以下两种方式配置:
全局开启校验
如果需要项目内所有接口默认禁止传入未声明的参数,直接在你的Grape API基类中添加配置:
class BaseAPI < Grape::API # 全局开启严格参数校验 strict_param_validation true format :json # 自定义捕获未知参数异常,返回你需要的406状态码 rescue_from Grape::Exceptions::UnknownParameters do |e| error!({ error: '请求包含未声明的非法参数' }, 406) end end
单个接口/局部范围开启校验
如果不需要全局生效,仅要给指定接口或者资源组开启校验,有两种写法:
- 在对应资源节点上配置:
resources :endpoint do # 仅当前资源下的所有接口开启严格参数校验 strict_param_validation true desc 'Fetches all content for this endpoint' params do optional :attr1, type: Integer optional :attr2, type: String optional :attr3, type: String end get do # 接口业务逻辑 end end
- 仅给单个接口的params块开启:
desc 'Fetches all content for this endpoint' # 仅当前params块生效严格校验 params strict: true do optional :attr1, type: Integer optional :attr2, type: String optional :attr3, type: String end get do # 接口业务逻辑 end
注意:如果接口存在嵌套参数定义,严格校验会自动作用于嵌套参数层级,无需额外配置。
内容的提问来源于stack exchange,提问作者MrKickass
相关产品推荐
相关产品推荐

