博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring异常处理
阅读量:6854 次
发布时间:2019-06-26

本文共 4407 字,大约阅读时间需要 14 分钟。

还是上次数据不能为空的问题,写到了C层测试。

先写一行测试代码,先期待一个200,但是我们是知道的,因为没有学科类别,这肯定会抛出异常,我们就是想看看Spring捕获这个异常之后给出的反馈是什么状态码。

@Testpublic void saveTest() throws Exception {    logger.debug("基础测试数据准备");    MeasurementUnitCategory measurementUnitCategory = new MeasurementUnitCategory();    String json = JSON.toJSONString(measurementUnitCategory);    this.mockMvc.perform(post(baseUrl)                        .header(xAuthKey, xAuthToken)                        .contentType(MediaType.APPLICATION_JSON_UTF8)                        .content(json))                .andExpect(status().isOk());}

测试一下,果然,控制台报错。

但是看一下报错信息,发现并不是我们期待的一个错误的状态码,而是200。同时下面还有异常抛出。

这说明Spring为我们抛出了这个DataIntegrityViolationException异常,但是却没有帮我们处理,这就需要我们手动处理然后返回给前台状态码。

MockHttpServletResponse:           Status = 200    Error message = null          Headers = {
X-Content-Type-Options=[nosniff], X-XSS-Protection=[1; mode=block], Cache-Control=[no-cache, no-store, max-age=0, must-revalidate], Pragma=[no-cache], Expires=[0], X-Application-Context=[application:-1], Content-Type=[application/json;charset=UTF-8], x-auth-token=[1b2b8d9f-3457-4277-879e-2ada48e3599e]} Content type = application/json;charset=UTF-8 Body = {
"id":8,"name":"","username":"usersdfdfwef23dfvdfwewef","mobile":"","pinyin":null,"createTime":1528338758059,"updateTime":1528338758059,"status":0,"department":{
"id":1,"name":"内蒙古自治区管理部门","code":"","postalCode":"","address":"","legalName":"","legalPhone":"","registrantName":"","registrantPhone":"","registrantTel":null,"registrantMail":"","phone":"","pinyin":"neimengguzishiquguanglibumeng","registerDate":null,"createTime":1528338752423,"updateTime":1528338752423,"status":null,"createUser":null,"departmentType":{
"id":1,"name":"管理部门","pinyin":"guanlibumen","createTime":1528338751963,"updateTime":1528338751963,"createUser":null},"district":{
"id":1,"districtType":{
"id":1,"name":"省","pinyin":"sheng"},"name":"内蒙古自治区","createUser":null,"pinyin":"neimengguzizhiqu","createTime":null,"updateTime":null},"checkAbility":false,"outOfRange":null,"standard":false},"roles":[],"createUser":null,"updateUser":null} Forwarded URL = null Redirected URL = null Cookies = []org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statementCaused by: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statementCaused by: org.hibernate.exception.ConstraintViolationException: could not execute statementCaused by: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "DISCIPLINE_ID"; SQL statement:insert into measurement_unit_category (id, discipline_id, is_asc) values (null, ?, ?) [23502-194]

理论上我们所有的异常都是由M层抛出,直接捕获或全局异常处理,是不会将异常抛给控制器的。

所以,我们需要全局异常处理,M层抛出异常,直接处理,返回xx状态码,而不将异常抛给控制器。

/** * 手动捕获数据冲突异常,经测试,该异常系由Spring抛出,但未捕获 * @return HttpStatus.CONFLICT * 冲突错误,409 * 参考: * https://stackoverflow.com/questions/37248719/couldnt-catch-dataintegrityviolationexception-with-spring-data-rest */@ExceptionHandler(value = DataIntegrityViolationException.class)public ResponseEntity
dataIntegrityViolationException(HttpServletRequest httpServletRequest, Exception exception) { logger.error("---数据不合法:---Host {} invokes url {} ERROR: {}", httpServletRequest.getRemoteHost(), httpServletRequest.getRequestURL(), exception.getMessage()); return new ResponseEntity<>(new JsonErrorResult(httpServletRequest, exception), HttpStatus.CONFLICT);}

我这里对状态码也不是很熟悉,去StackOverflow上看到一个老哥是和我遇到了一样的问题,他解决的方案是捕获异常返回409(冲突),。

异常捕获后,修改测试,期待状态码为409Conflict

@Testpublic void saveTest() throws Exception {    logger.debug("基础测试数据准备");    MeasurementUnitCategory measurementUnitCategory = new MeasurementUnitCategory();    String json = JSON.toJSONString(measurementUnitCategory);    logger.debug("无学科的计量单位类别保存,期待409,冲突状态码");    this.mockMvc.perform(post(baseUrl)                        .header(xAuthKey, xAuthToken)                        .contentType(MediaType.APPLICATION_JSON_UTF8)                        .content(json))                .andExpect(status().isConflict());}

重新运行单元测试,通过。

clipboard.png

转载地址:http://kffyl.baihongyu.com/

你可能感兴趣的文章
设计模式 总揽 通过这篇随笔可以访问所需要了解的设计模式
查看>>
Java HotSpot VM中的JIT编译
查看>>
敏捷软件测试--初见
查看>>
NSLayoutConstraint
查看>>
深入浅出: 大小端模式
查看>>
走在网页游戏开发的路上(十一)
查看>>
[Linux shell]查找某目录下文件是否包含某个字符串
查看>>
Java的RMI远程方法调用实现和应用
查看>>
线程间共享数据无需竞争
查看>>
记一次通宵加班
查看>>
iOS7 兼容适配 如何判断版本号
查看>>
Hibernate懒加载解析
查看>>
字符串匹配与KMP算法实现
查看>>
菜鸟学自动化测试(七)----selenium RC 工作原理
查看>>
ACM 要学
查看>>
C++之:模板元编程(二) 模板形参
查看>>
甲骨文宣布正式介入存储业务 超融合架构须基于对业务的深刻了解
查看>>
[华为机试练习题]25.圆桌游戏
查看>>
Android学习笔记(16):绝对布局AbsoluteLayout、常用距离单位
查看>>
[华为机试真题]66.单词搜索
查看>>