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

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";
	}
}

1.1.2.错误页面

html 复制代码
<!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.创建全局异常处理器

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");
		}else if(ex instanceof NullPointerException){
			mv.setViewName("error2");
		}
		mv.addObject("error", ex.toString());
		
		return mv;
	}
}

1.2.3.错误页面

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>

1.3.整合ajax全局异常处理

1.3.1.创建全局异常处理器

java 复制代码
@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启动器

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

2.2.编写业务代码

2.2.1.dao

java 复制代码
@Repository
public class UserDaoImpl {

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

2.2.2.service

java 复制代码
@Service
public class UserServiceImpl {

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

2.2.3.app

java 复制代码
@SpringBootApplication
public class App {

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

2.3.整合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();
	}
}
相关推荐
苹果醋336 分钟前
快速玩转 Mixtral 8x7B MOE大模型!阿里云机器学习 PAI 推出最佳实践
spring boot·nginx·毕业设计·layui·课程设计
程序员大金41 分钟前
基于SpringBoot+Vue+MySQL的装修公司管理系统
vue.js·spring boot·mysql
姜学迁1 小时前
Rust-枚举
开发语言·后端·rust
爱学习的小健2 小时前
MQTT--Java整合EMQX
后端
北极小狐2 小时前
Java vs JavaScript:类型系统的艺术 - 从 Object 到 any,从静态到动态
后端
【D'accumulation】2 小时前
令牌主动失效机制范例(利用redis)注释分析
java·spring boot·redis·后端
2401_854391082 小时前
高效开发:SpringBoot网上租赁系统实现细节
java·spring boot·后端
Cikiss2 小时前
微服务实战——SpringCache 整合 Redis
java·redis·后端·微服务
wxin_VXbishe2 小时前
springboot合肥师范学院实习实训管理系统-计算机毕业设计源码31290
java·spring boot·python·spring·servlet·django·php
Cikiss2 小时前
微服务实战——平台属性
java·数据库·后端·微服务