天天看点

SpringMVC中@RequestBody引起的400异常处理,返回校验失败具体信息

使用<code>@RequestBody</code>接收一个json数据的时候,如果传入的参数不符合条件,就会直接返回400的error page. 但究竟是为什么会400并没有抛出来。这对大量参数字段的我们来说,排错很困难,所以应该返回出错的原因。

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.

具体就是当spring的<code>@RequestBody</code>注解进行marshall操作的时候,如果jackson跑出异常,就会抛出一个叫做<code>HttpMessageNotReadableException</code>的异常,那么我们只要捕获并返回这个异常就可以了。

最简单是在controller里加一个错误处理的方案:

如果想要对所有的controller生效,那么需要一个注解<code>@ControllerAdvice</code>:

所以,可以处理你想要的异常:

唯有不断学习方能改变!

-- <b>Ryan Miao</b>