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);
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值