SpringBoot 异常处理与单元测试

一、SpringBoot中异常处理
1.SpringBoot中对于异常处理提供了五种处理方式
1.1自定义错误页面
SpringBoot默认的处理异常的机制:SpringBoot默认的已经提供了一套处理异常的机制,一旦程序中出现了异常SpringBoot会向/error的url发送请求。在SpringBoot中提供了一个叫BasicExceptionController 来处理/error请求,然后跳转到默认显示异常的页面来展示异常信息。
在这里插入图片描述
如果我们需要将所有的异常统一跳转到自定义的错误页面,需要在src/main/resource/templates/error.html页面。注意:名称必须交error

1.2@ExceptionHandle注解处理异常
1.2.1Controller

import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

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

	/**
	 * java.lang.ArithmeticException
	 * 该方法需要返回一个ModelAndView,目的是可以让我们封装异常信息以及视图的指定
	 * @param e 会奖产生异常对象注入到方法中
	 * @return
	 */
	@ExceptionHandler(value=java.lang.ArithmeticException.class)
	public ModelAndView arithmeticExceptionHandler(Exception e) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("error",e.toString());
		mv.setViewName("error1");
		return mv;
	}
	/**
	 * java.lang.NullPointerException
	 * 该方法需要返回一个ModelAndView,目的是可以让我们封装异常信息以及视图的指定
	 * @param e 会奖产生异常对象注入到方法中
	 * @return
	 */
	@ExceptionHandler(value=java.lang.NullPointerException.class)
	public ModelAndView nullPointerExceptionHandler(Exception e) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("error",e.toString());
		mv.setViewName("error2");
		return mv;
	}
}

1.2.2视图页面

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

1.3@ControllerAdvice+@ExceptionHandler注解处理异常
需要创建一个能够处理异常的全局异常类,在该类加上@ControllerAdvice

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

/**
 * 全局异常处理类
 * 
 * @author Administrator
 *
 */
@ControllerAdvice
public class GlobalException {

	/**
	 * java.lang.ArithmeticException 该方法需要返回一个ModelAndView,目的是可以让我们封装异常信息以及视图的指定
	 * 
	 * @param e 会奖产生异常对象注入到方法中
	 * @return
	 */
	@ExceptionHandler(value = java.lang.ArithmeticException.class)
	public ModelAndView arithmeticExceptionHandler(Exception e) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("error", e.toString());
		mv.setViewName("error1");
		return mv;
	}

	/**
	 * java.lang.NullPointerException 该方法需要返回一个ModelAndView,目的是可以让我们封装异常信息以及视图的指定
	 * 
	 * @param e 会奖产生异常对象注入到方法中
	 * @return
	 */
	@ExceptionHandler(value = java.lang.NullPointerException.class)
	public ModelAndView nullPointerExceptionHandler(Exception e) {
		ModelAndView mv = new ModelAndView();
		mv.addObject("error", e.toString());
		mv.setViewName("error2");
		return mv;
	}
}

1.4配置SimpleMappingExceptionResolver处理异常

在全局异常类中添加一个方法完成统一处理。
只能做异常映射,不能传递异常信息

import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

/**
 * 通过SimpleMappingExceptionResolver做全局异常处理类
 * 
 * @author Administrator
 *
 */
@Configuration
public class GlobalException {

	/**
	 * 
	 * 该方法必须要有返回值,返回值类型必须是:SimpleMappingExceptionResolver
	 * 
	 */
	@Bean
	public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver() {
		SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
		Properties mappings = new Properties();
		/**
		 * 参数一:异常的类型,注意必须是异常类型的全名 参数二:视图名称
		 */
		mappings.put("java.lang.ArithmeticException", "error1");
		mappings.put("java.lang.NullPointerException", "error2");
		// 设置异常与视图映射信息的
		resolver.setExceptionMappings(mappings);
		return resolver;
	}

}

1.5自定义HandlerExcetionResver处理异常
需要在全局异常处理类中实现HandlerExceptionResolver 方法

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

/**
 * 通过实现HandlerExceptionResolver接口做全局异常处理类
 * 
 * @author Administrator
 *
 */
@Configuration
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;
	}
 
}

二 SpringBoot整合Junit测试
1.创建项目
2.修改pom文件添加jar包

<!-- 添加junit环境的jar包 -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>

3.编写业务代码
3.1Dao

@Repository
public class UserDaoImpl {

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

}

3.2业务层

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

4.使用SpringBoot整合Junit做单元测试
编写测试类

/**
 * SpringBoot 测试类
 * @RunWith:启动器
 * SpringJUnit4ClassRunner.class 让junit与spring环境进行整合
 * 
 * @SpringBootTest(classes= {Application.class}) 1.当前类为SpringBoot的测试类
 * @SpringBootTest(classes= {Application.class}) 2.加载SpringBoot启动类,启动springboot
 * 
 * junit与spring整合 @Contextconfiguartion("classpath:applicationContxt.xml")
 * 
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes= {Application.class})
public class UserServiceTest {
	
	@Autowired
	private UserServiceImpl userServiceImpl;
	
	@Test
	public void testAddUser() {
		this.userServiceImpl.addUser();
	}
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值