问题

使用@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. 【NLP】Python NLTK 走进大秦帝国
  2. 深入理解定时器系列第二篇——被誉为神器的requestAnimationFrame
  3. 用Javascript模拟微信飞机大战游戏
  4. PHP图片裁剪_图片缩放_PHP生成缩略图
  5. kafka及zookeeper安装
  6. Html 网页布局(一)
  7. Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number. An example is the root-to-leaf path1->2->3which represents the number123. Find the total sum of a
  8. 磁盘分区、格式化、挂载[转自vbird]
  9. 【PHP】金额数字转换成大写形式
  10. 源码解析之setContentView
  11. myeclipse web 包名保留字与servlet冲突
  12. Java多线程(一) 多线程的基本使用
  13. vue-cli 中 使用vue-resource 输出后台数据
  14. main函数是主线程吗
  15. 两个数字比较大小的方法 (分别应用if-else和条件运算符实现)
  16. fcagte.exe应用程序错误
  17. MySQL中Checkpoint技术
  18. self.xxx = nil 可以等效于[_xxx release] _xxx= nil 么
  19. 指定nvm的默认版本号
  20. SUSE11&12 永久关闭防火墙

热门文章

  1. 面试之MySQL基本命令
  2. DOM范围
  3. java反射的理解与应用(某大神博客中看到的博文,写的真的太好了,果断转载作为笔记)
  4. 性能秒杀log4net的NLogger日志组件(附测试代码与NLogger源码)
  5. 税号输入框 将input框中的输入自动转化成半角大写
  6. VS2008 + WDK 配置 及其编译错误
  7. ASP.NET MVC5 实现分页查询
  8. 对synchronized关键字的理解
  9. hive取数时如果遇到这种报错
  10. 【转】jqGrid学习之参数