当前位置: 首页 > news >正文

Spring Boot异常处理和单元测试

1.SpringBoot异常处理

1.1.自定义错误页面

SpringBoot默认的处理异常的机制:SpringBoot 默认的已经提供了一套处理异常的机制。一旦程序中出现了异常 SpringBoot 会向/error 的 url 发送请求。在 springBoot 中提供了一个叫 BasicErrorController 来处理/error 请求,然后跳转到默认显示异常的页面来展示异常信息

在这里插入图片描述

如 果我 们 需 要 将 所 有 的 异 常 同 一 跳 转 到 自 定 义 的 错 误 页 面 , 需 要 再src/main/resources/

templates 目录下创建 error.html 页面。注意:名称必须叫 error

1.1.1.controller

/*** SpringBoot处理异常方式一:自定义错误页面*/
@Controller
public class DemoController {@RequestMapping("/show")public String showInfo(){String str = null;str.length();return "index";}@RequestMapping("/show2")public String showInfo2(){int a = 10/0;return "index";}
}

1.1.2.错误页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示页面</title>
</head>
<body>出错了,请与管理员联系。。。<span th:text="${error}"></span>
</body>
</html>

1.2.整合web访问全局异常处理器

1.2.1.处理思路

在这里插入图片描述

1.2.2.创建全局异常处理器

/*** 通过实现HandlerExceptionResolver接口做全局异常处理*/
@Component
public class GlobalException implements HandlerExceptionResolver {@Overridepublic ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,Exception ex) {ModelAndView mv = new ModelAndView();//判断不同异常类型,做不同视图跳转if(ex instanceof ArithmeticException){mv.setViewName("error1");}else if(ex instanceof NullPointerException){mv.setViewName("error2");}mv.addObject("error", ex.toString());return mv;}
}

1.2.3.错误页面

error1.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示页面-ArithmeticException</title>
</head>
<body>出错了,请与管理员联系。。。<span th:text="${error}"></span>
</body>
</html>

error2.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>错误提示页面-NullPointerException</title>
</head>
<body>出错了,请与管理员联系。。。<span th:text="${error}"></span>
</body>
</html>

1.3.整合ajax全局异常处理

1.3.1.创建全局异常处理器

@ControllerAdvice
public class AjaxGlobalExceptionHandler {/*** 处理全局异常* @param exception   异常* @return Map<String, Object>*/@ResponseBody@ExceptionHandler(value = Exception.class)public Map<String, Object> errorHandler(Exception exception) {Map<String, Object> map = new HashMapMap<>();map.put("status", 500);map.put("msg", exception.getMessage());return map;}
}

2.Spring Boot整合Junit

2.1.Junit启动器

		<!--junit启动器 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId></dependency>

2.2.编写业务代码

2.2.1.dao

@Repository
public class UserDaoImpl {public void saveUser(){System.out.println("insert into users.....");}
}

2.2.2.service

@Service
public class UserServiceImpl {@Autowiredprivate UserDaoImpl userDaoImpl;public void addUser(){this.userDaoImpl.saveUser();}
}

2.2.3.app

@SpringBootApplication
public class App {public static void main(String[] args) {SpringApplication.run(App.class, args);}
}

2.3.整合Junit

/***  main方法:*		ApplicationContext ac=new *       			ClassPathXmlApplicationContext("classpath:applicationContext.xml");*  junit与spring整合:*      @RunWith(SpringJUnit4ClassRunner.class):让junit与spring环境进行整合*   	@Contextconfiguartion("classpath:applicationContext.xml")  */
@RunWith(SpringJUnit4ClassRunner.class) 
@SpringBootTest(classes={App.class})
public class UserServiceTest {@Autowiredprivate UserServiceImpl userServiceImpl;@Testpublic void testAddUser(){this.userServiceImpl.addUser();}
}

相关文章:

  • 变换,动画
  • 计算机网络 八股
  • AJAX-常用请求方法和数据提交
  • IP-guard邮件管控再升级,记录屏幕画面,智能阻断泄密邮件
  • 零基础学习JS--基础篇--索引集合类
  • Xilinx 7系列FPGA的配置流程
  • QT----写完的程序打包为APK在自己的手机上运行
  • 设计MySQL数据表的几个注意点
  • python:布伊山德U检验(Buishand U test,BUT)突变点检测(以NDVI时间序列为例)
  • 「AI工程师」数据处理与分析-工作指导
  • c语言,大宗撮合交易中心系统核心模块代码
  • Toyota Programming Contest 2024#3(AtCoder Beginner Contest 344)(A~C)
  • 【C/C++】常量指针与指针常量的深入解析与区分(什么是const int * 与 int * const ?)
  • [渗透教程]-013-嗅探工具-wireshark操作
  • python脚本批量关闭exe文件
  • @angular/forms 源码解析之双向绑定
  • 【399天】跃迁之路——程序员高效学习方法论探索系列(实验阶段156-2018.03.11)...
  • Docker 1.12实践:Docker Service、Stack与分布式应用捆绑包
  • JS专题之继承
  • maya建模与骨骼动画快速实现人工鱼
  • mysql innodb 索引使用指南
  • Python 使用 Tornado 框架实现 WebHook 自动部署 Git 项目
  • Python连接Oracle
  • 从重复到重用
  • 反思总结然后整装待发
  • 工作手记之html2canvas使用概述
  • 七牛云假注销小指南
  • 如何合理的规划jvm性能调优
  • 提醒我喝水chrome插件开发指南
  • ​​​​​​​GitLab 之 GitLab-Runner 安装,配置与问题汇总
  • $NOIp2018$劝退记
  • (13)Hive调优——动态分区导致的小文件问题
  • (32位汇编 五)mov/add/sub/and/or/xor/not
  • (Repost) Getting Genode with TrustZone on the i.MX
  • (附源码)ssm考试题库管理系统 毕业设计 069043
  • (教学思路 C#之类三)方法参数类型(ref、out、parmas)
  • (三分钟了解debug)SLAM研究方向-Debug总结
  • (四)Android布局类型(线性布局LinearLayout)
  • (转) ns2/nam与nam实现相关的文件
  • (转载)虚函数剖析
  • .a文件和.so文件
  • .NET “底层”异步编程模式——异步编程模型(Asynchronous Programming Model,APM)...
  • .net core Swagger 过滤部分Api
  • .NET 表达式计算:Expression Evaluator
  • @zabbix数据库历史与趋势数据占用优化(mysql存储查询)
  • [2010-8-30]
  • [2017][note]基于空间交叉相位调制的两个连续波在few layer铋Bi中的全光switch——
  • [ArcPy百科]第三节: Geometry信息中的空间参考解析
  • [BUG]vscode插件live server无法自动打开浏览器
  • [codeforces]Checkpoints
  • [c语言]小课堂 day2
  • [GN] 后端接口已经写好 初次布局前端需要的操作(例)
  • [Leetcode] 寻找数组的中心索引
  • [MySQL光速入门]003 留点作业...
  • [NEWS] J2SE5.0来了