SpringMVC中@RequestBody引起的400异常处理,返回校验失败具体信息
问题
使用@RequestBody
接收一个json数据的时候,如果传入的参数不符合条件,就会直接返回400的error page. 但究竟是为什么会400并没有抛出来。这对大量参数字段的我们来说,排错很困难,所以应该返回出错的原因。
Resolve
This was raised as an issue with Spring SPR-7439 - JSON (jackson) @RequestBody marshalling throws awkward exception - which was fixed in Spring 3.1M2 by having Spring throw a org.springframework.http.converter.HttpMessageNotReadableException in the case of a missing or invalid message body.
以上来自stackoverflow.
具体就是当spring的@RequestBody
注解进行marshall操作的时候,如果jackson跑出异常,就会抛出一个叫做HttpMessageNotReadableException
的异常,那么我们只要捕获并返回这个异常就可以了。
具体做法
最简单是在controller里加一个错误处理的方案:
@ExceptionHandler({HttpMessageNotReadableException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public CodeMsg resolveException(HttpMessageNotReadableException errors) {
return CodeMsg.error(errors.getMessage());
}
如果想要对所有的controller生效,那么需要一个注解@ControllerAdvice
:
@ControllerAdvice
public class GeneralHandler {
@ExceptionHandler
public ModelAndView handleException (NoSuchRequestHandlingMethodException ex) {
ModelAndView mav = new ModelAndView();
...
return mav;
}
}
所以,可以处理你想要的异常:
@ExceptionHandler
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public RestError resolveBindingException ( MethodArgumentNotValidException methodArgumentNotValidException, Locale locale )
{
BindingResult bindingResult = methodArgumentNotValidException.getBindingResult();
return getRestError(bindingResult, locale);
}
关注我的公众号

分类:
spring
标签:
springboot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了