SpringBoot进行全局异常处理

使用@ExceptionHandler 加@ControllerAdvice 注解

模拟异常发生

@RestController
@RequestMapping("/exception")
public class ExceptionController {
          
   

    @RequestMapping("/show1")
    public String showInfo1() {
          
   
        String msg = null;
        msg.length(); // NullPointerException
        return "success";
    }
    
    @RequestMapping("/show2")
    public String showInfo2() {
          
   
        int a = 0;
        int b = 100;
        System.out.println(b / a); //ArithmeicExpetion
        return "success";
    }
}

全局异常处理类

@ControllerAdvice
public class GlobalException {
          
   
	
	@ExceptionHandler(value = {
          
    NullPointerException.class })
	public ModelAndView nullPointerExceptionHandler(Exception e) {
          
   
		ModelAndView view = new ModelAndView();
        view.setViewName("error");
        view.addObject("error","空指针异常");
		return view;
	}
	
	
    @ExceptionHandler(value = {
          
   ArithmeticException.class})
    public ModelAndView arithmeticExceptionHandler(Exception e){
          
   
        ModelAndView view = new ModelAndView();
        view.setViewName("error");
        view.addObject("error","算数运算异常");
        return view;
    }
}

跳转的页面(这里使用了thymeleaf)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
	<h1>系统错误页面</h1>
	<span th:text="${error}"></span>
</body>
</html>

测试结果:

经验分享 程序员 微信小程序 职场和发展