zoukankan      html  css  js  c++  java
  • 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);
    }
    
  • 相关阅读:
    项目管理5大过程9大知识域44个定义
    linux centos6.5 修改ip地址
    .Net 6 已知问题集
    第二次阅读作业——程志
    采访大四学长整理笔记
    c#
    团队作业三两感想 by 程志
    搞定3G上网
    高焕堂Android應用框架原理與程式設計代码补遗(一)
    要素类属性内容全角换半角
  • 原文地址:https://www.cnblogs.com/woshimrf/p/6602690.html
Copyright © 2011-2022 走看看