SpringMVC参数校验(针对`@RequestBody`返回`400`)

SpringMVC参数校验(针对@RequestBody返回400

前言

习惯别人帮忙做事的结果是自己不会做事了。一直以来,spring帮我解决了程序运行中的各种问题,我只要关心我的业务逻辑,设计好我的业务代码,返回正确的结果即可。直到遇到了400

spring返回400的时候通常没有任何错误提示,当然也通常是参数不匹配。这在参数少的情况下还可以一眼看穿,但当参数很大是,排除参数也很麻烦,更何况,既然错误了,为什么指出来原因呢。好吧,springmvc把这个权力交给了用户自己。

springmvc异常处理

最开始的时候也想过自己拦截会出异常的method来进行异常处理,但显然不需要这么做。spring提供了内嵌的以及全局的异常处理方法,基本可以满足我的需求了。

1. 内嵌异常处理

如果只是这个controller的异常做单独处理,那么就适合绑定这个controller本身的异常。

具体做法是使用注解@ExceptionHandler.

在这个controller中添加一个方法,并添加上述注解,并指明要拦截的异常。

@RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)
public String saveOrUpdate(HttpServletResponse response, @RequestBody Order order){
    CodeMsg result = null;
    try {
        result = orderService.saveOrUpdate(order);
    } catch (Exception e) {
        logger.error("save failed.", e);
        return this.renderString(response, CodeMsg.error(e.getMessage()));
    }
    return this.renderString(response, result);
}

@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public CodeMsg messageNotReadable(HttpMessageNotReadableException exception, HttpServletResponse response){
    LOGGER.error("请求参数不匹配。", exception);
    return CodeMsg.error(exception.getMessage());
}

这里saveOrUpdate是我们想要拦截一样的请求,而messageNotReadable则是处理异常的代码。
@ExceptionHandler(HttpMessageNotReadableException.class)表示我要拦截何种异常。在这里,由于springmvc默认采用jackson作为json序列化工具,当反序列化失败的时候就会抛出HttpMessageNotReadableException异常。具体如下:

{
   
  "code": 1,
  "msg": "Could not read JSON: Failed to parse Date value '2017-03-' (format: \"yyyy-MM-dd HH:mm:ss\"): Unparseable date: \"2017-03-\" (through reference chain: com.test.modules.order.entity.Order[\"serveTime\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Failed to parse Date value '2017-03-' (format: \"yyyy-MM-dd HH:mm:ss\"): Unparseable date: \"2017-03-\" (through reference chain: com.test.modules.order.entity.Order[\"

你可能感兴趣的:(spring,spring,mvc)