SpringBoot异常处理和单元测试

SpringBoot异常处理

自定义错误页面

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

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

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

controller

java 复制代码
/**
 * 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";
	}
}

错误页面

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

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

创建全局异常处理器

java 复制代码
/**
 * 通过实现HandlerExceptionResolver接口做全局异常处理
 */
@Component
public class GlobalException implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,Exception ex) {
		ModelAndView mv = new ModelAndView();
		//判断不同异常类型,做不同视图跳转
		if(ex instanceof ArithmeticException){
			mv.setViewName("error1");
		}
		
		if(ex instanceof NullPointerException){
			mv.setViewName("error2");
		}
		mv.addObject("error", ex.toString());
		
		return mv;
	}
}

错误页面

error1.html

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

error2.html

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

整合ajax全局异常处理

创建全局异常处理器

java 复制代码
@ControllerAdvice
public class AjaxGlobalException {
 
 
    /**
     * 处理全局异常
     * @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;
    }
}

Spring Boot整合Junit

Junit启动器

xml 复制代码
		<!--junit启动器 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
		</dependency>

编写业务代码

dao

java 复制代码
@Repository
public class UserDaoImpl {

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

service

java 复制代码
@Service
public class UserServiceImpl {

	@Autowired
	private UserDaoImpl userDaoImpl;
	
	public void addUser(){
		this.userDaoImpl.saveUser();
	}
}

app

java 复制代码
@SpringBootApplication
public class App {

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

整合Junit

java 复制代码
/**
 *  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 {

	@Autowired
	private UserServiceImpl userServiceImpl;
	
	@Test
	public void testAddUser(){
		this.userServiceImpl.addUser();
	}
}
相关推荐
程序员张31 小时前
SpringBoot计时一次请求耗时
java·spring boot·后端
程序员岳焱7 小时前
Java 与 MySQL 性能优化:Java 实现百万数据分批次插入的最佳实践
后端·mysql·性能优化
麦兜*7 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
KK溜了溜了8 小时前
JAVA-springboot 整合Redis
java·spring boot·redis
大只鹅8 小时前
解决 Spring Boot 对 Elasticsearch 字段没有小驼峰映射的问题
spring boot·后端·elasticsearch
ai小鬼头8 小时前
AIStarter如何快速部署Stable Diffusion?**新手也能轻松上手的AI绘图
前端·后端·github
天河归来8 小时前
使用idea创建springboot单体项目
java·spring boot·intellij-idea
IT_10248 小时前
Spring Boot项目开发实战销售管理系统——数据库设计!
java·开发语言·数据库·spring boot·后端·oracle
bobz9659 小时前
动态规划
后端
stark张宇9 小时前
VMware 虚拟机装 Linux Centos 7.9 保姆级教程(附资源包)
linux·后端