如何让RestEasy对错误查询参数返回HTTP 400错误而非404
RestEasy 参数解析异常返回404问题解决方案
这个属于RestEasy的默认可配置行为,并非框架bug。
问题根因
RestEasy早期版本默认将查询参数解析/转换失败归类到资源匹配失败范畴,所以默认返回404状态码,甚至会捕获自定义ParamConverter抛出的BadRequestException,重新包装为NotFoundException抛出。
修复配置
RestEasy 3.0.16及以上版本提供了专门的配置项修改该行为,按需添加对应配置即可:
1. 基础参数转换失败返回400配置
配置resteasy.param.converter.failure.status.code为400,指定参数转换失败的默认状态码:
- 基于
web.xml部署的项目添加如下上下文参数:
<context-param> <param-name>resteasy.param.converter.failure.status.code</param-name> <param-value>400</param-value> </context-param>
- 基于
Application类注册JAX-RS服务的场景,重写getProperties方法添加配置:
@Override public Map<String, Object> getProperties() { Map<String, Object> properties = new HashMap<>(); properties.put("resteasy.param.converter.failure.status.code", 400); // 保留自定义异常原始状态码的配置 properties.put("resteasy.original.webapplicationexception.behavior", true); return properties; }
- Spring Boot/Quarkus集成场景在对应配置文件中添加配置即可:
普通Spring Boot集成:resteasy.param.converter.failure.status.code=400
Quarkus集成:quarkus.resteasy.param-converter-failure-status-code=400
2. 保留自定义异常原始状态码配置
如果需要让自定义ParamConverter抛出的BadRequestException不被框架覆盖,额外添加resteasy.original.webapplicationexception.behavior配置为true即可,配置方式和上面的参数一致。
内容的提问来源于stack exchange,提问作者martins
相关产品推荐
相关产品推荐

