/**PageBeginHtml Block Begin **/ /***自定义返回顶部小火箭***/ /*生成博客目录的JS 开始*/ /*生成博客目录的JS 结束*/

Spring Boot 异常处理与单元测试


一:SpringBoot 中 异常处理方式

1:Springboot 中对 异常处理提供了五种处理方式


     1.自定义错误页面


image

            一:展示springboot 默认的错误 页面内容

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


1:展示错误效果

image


2:展示代码:

DemoController

package com.alan.exception.controller;
/**
 * @author Alan_liu
 * @Create 2021-04-16 22:32
 * @PROJECT_NAME SpringBootException1
 * @PACKAGE_NAME com.alan.exception.controller
 * @FILE_NAME DemoController.java
 */

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *@program: SpringBootException1
 *@description:  springboot  处理异常方式一:自定义错误页面
 *@author: Alan_Liu
 *@create: 2021-04-16 22:32
 */
@Controller
public class DemoController {

	 /***
	  *
	  *
	  *@Param: []
	  *@return
	  *@throws
	  *@author Alan_Liu
	  *@date   2021/4/16 22:34
	  *
	  **/
	@RequestMapping("/show")
	public String showInfo(){
		String str=null;
		str.length();
		return "index";
	}





}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>

ExceptionApplication

package com.alan.exception;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExceptionApplication {

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

}






            二:展示自定义错误页面 显示效果

image


1:展示自定义错误页面访问效果

声明:springboot的自定义错误 页面必须是 error.html

如 果 我 们 需 要 将 所 有 的 异 常 同 一 跳 转 到 自 定 义 的 错 误 页 面 , 需 要 再 src/main/resources/templates 目录下创建 error.html 页面。注意:名称必须叫 error

image

2:代码展示:

pom,xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.alan</groupId>
    <artifactId>exception</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>exception</name>
    <description>Springboot exception</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

ExceptionApplication

package com.alan.exception;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExceptionApplication {

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

}

DemoController

package com.alan.exception.controller;
/**
 * @author Alan_liu
 * @Create 2021-04-16 22:32
 * @PROJECT_NAME SpringBootException1
 * @PACKAGE_NAME com.alan.exception.controller
 * @FILE_NAME DemoController.java
 */

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *@program: SpringBootException1
 *@description:  springboot  处理异常方式一:自定义错误页面
 *@author: Alan_Liu
 *@create: 2021-04-16 22:32
 */
@Controller
public class DemoController {

	 /***
	  *
	  *
	  *@Param: []
	  *@return
	  *@throws
	  *@author Alan_Liu
	  *@date   2021/4/16 22:34
	  *
	  **/
	@RequestMapping("/show")
	public String showInfo(){
		String str=null;
		str.length();
		return "index";
	}





}

error.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>错误提示页面</title>
</head>
<body>
   <hr />
   <br>
   <br>
   <br>
   出错了,请于管理员联系。
   XXXXXX@XX.COM.CN
   <br>
   <br>
   <br>
   <br>
   <!--/*@thymesVar id="exception" type=""*/-->
   <span  th:text="${exception}"> </span>
    
   <br>
   <br>
   <hr/>
</body>
</html>

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>







     2:@ExceptionHandle 注解处理异常

1: 代码结构图

image



2:访问请求效果图:

1:访问NullPointerException指定错误页面效果图

image

2:访问 ArithmeticException指定错误页面效果图

image

3:访问不存在的方法:跳转指定的默认错误页面展示效果图

image


3:源代码展示


pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.Alan</groupId>
    <artifactId>exception</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>exception</name>
    <description>SpringBoot Exception</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>


DemoController
package com.alan.exception.controller;
/**
 * @author Alan_liu
 * @Create 2021-04-16 22:32
 * @PROJECT_NAME SpringBootException1
 * @PACKAGE_NAME com.alan.exception.controller
 * @FILE_NAME DemoController.java
 */

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;

/**
 *@program: SpringBootException1
 *@description:  springboot  处理异常方式一:自定义错误页面
 *@author: Alan_Liu
 *@create: 2021-04-16 22:32
 */
@Controller
public class DemoController {

   /***
    *  java.lang.ArithmeticException
    *   该方法需要返回一个 modeandview :目的是可以让我们封装一个异常信息以及视图的指定
    *
    *@Param: [e]    exception e :会将产生异常对象注入到方法中
    *@return
    *@throws
    *@author Alan_Liu
    *@date   2021/4/17 20:08
    *
    **/
    @ExceptionHandler(value={java.lang.ArithmeticException.class})
	public ModelAndView arithmeticExceptionHandler(Exception e){
	    ModelAndView mv =new ModelAndView();
	    mv.addObject("error",e.toString());
	    mv.setViewName("ArithmeticExceptionError");
    	return mv;
	}

	/***
	 *  java.lang.NullPointerException
	 *   该方法需要返回一个 modeandview :目的是可以让我们封装一个异常信息以及视图的指定
	 *
	 *@Param: [e]    exception e :会将产生异常对象注入到方法中
	 *@return
	 *@throws
	 *@author Alan_Liu
	 *@date   2021/4/17 20:08
	 *
	 **/
	@ExceptionHandler(value={java.lang.NullPointerException.class})
	public ModelAndView nullPointerException(Exception e){
		ModelAndView mv =new ModelAndView();
		mv.addObject("error",e.toString());
		mv.setViewName("nullPointerExceptionError");
		return mv;
	}


	/***
	  *
	  *
	  *@Param: []
	  *@return
	  *@throws
	  *@author Alan_Liu
	  *@date   2021/4/16 22:34
	  *
	  **/
	@RequestMapping("/show")
	public String showInfo(){
		String str=null;
		str.length();
		return "index";
	}

	/***
	 *
	 *
	 *@Param: []
	 *@return
	 *@throws
	 *@author Alan_Liu
	 *@date   2021/4/16 22:34
	 *
	 **/
	@RequestMapping("/show2")
	public String showInfo1(){
		int a=10/0;
		return "index";
	}




}


ExceptionApplication
package com.alan.exception;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExceptionApplication {

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

}

ArithmeticExceptionError.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>错误提示页面java.lang.ArithmeticException</title>
</head>
<body>
   <hr />
   <br>
   <br>
   <br>
   出错了,请于管理员联系。
   XXXXXX@XX.COM.CN
   <br>
   <br>
   <br>
   <br>
   <!--/*@thymesVar id="exception" type=""*/-->
   <span  th:text="${error}"> </span>
   <br>
   <br>
   <hr/>
</body>
</html>

error.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>错误提示页面</title>
</head>
<body>
   <hr />
   <br>
   <br>
   <br>
   出错了,请于管理员联系。
   XXXXXX@XX.COM.CN
   <br>
   <br>
   <br>
   <br>
   <!--/*@thymesVar id="exception" type=""*/-->
   <span  th:text="${exception}"> </span>
   <br>
   <br>
   <hr/>
</body>
</html>


index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>

nullPointerExceptionError.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>错误提示页面java.lang.NullPointerException</title>
</head>
<body>
   <hr />
   <br>
   <br>
   <br>
   出错了,请于管理员联系。
   XXXXXX@XX.COM.CN
   <br>
   <br>
   <br>
   <br>
   <!--/*@thymesVar id="exception" type=""*/-->
   <span  th:text="${error}"> </span>
   <br>
   <br>
   <hr/>
</body>
</html>

application.properties

image













     3:@ControllerAdivce + @ExceptionHandler 注解处理 异常


1:展示代码结构图

image

2:展示效果图:

image

image

image


3:代码内容

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.Alan</groupId>
    <artifactId>exception</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>exception</name>
    <description>SpringBoot Exception</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
GlobalException
package com.alan.exception.controller;
/**
 * @author Alan_liu
 * @Create 2021-04-17 21:23
 * @PROJECT_NAME SpringBootException3
 * @PACKAGE_NAME com.alan.exception.controller
 * @FILE_NAME null.java
 */

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

/**
 * 全局 异常处理类
 *@program: SpringBootException3
 *@description:
 *@author: Alan_Liu
 *@create: 2021-04-17 21:23
 */
@ControllerAdvice
public class GlobalException {
	/***
	 *  java.lang.ArithmeticException
	 *   该方法需要返回一个 modeandview :目的是可以让我们封装一个异常信息以及视图的指定
	 *
	 *@Param: [e]    exception e :会将产生异常对象注入到方法中
	 *@return
	 *@throws
	 *@author Alan_Liu
	 *@date   2021/4/17 20:08
	 *
	 **/
	@ExceptionHandler(value={ArithmeticException.class})
	public ModelAndView arithmeticExceptionHandler(Exception e){
		ModelAndView mv =new ModelAndView();
		mv.addObject("error",e.toString());
		mv.setViewName("ArithmeticExceptionError");
		return mv;
	}

	/***
	 *  java.lang.NullPointerException
	 *   该方法需要返回一个 modeandview :目的是可以让我们封装一个异常信息以及视图的指定
	 *
	 *@Param: [e]    exception e :会将产生异常对象注入到方法中
	 *@return
	 *@throws
	 *@author Alan_Liu
	 *@date   2021/4/17 20:08
	 *
	 **/
	@ExceptionHandler(value={NullPointerException.class})
	public ModelAndView nullPointerException(Exception e){
		ModelAndView mv =new ModelAndView();
		mv.addObject("error",e.toString());
		mv.setViewName("nullPointerExceptionError");
		return mv;
	}
}


UserController

package com.alan.exception.controller;
/**
 * @author Alan_liu
 * @Create 2021-04-17 21:16
 * @PROJECT_NAME SpringBootException3
 * @PACKAGE_NAME com.alan.exception.controller
 * @FILE_NAME null.java
 */

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *@program: SpringBootException3
 *@description:
 *@author: Alan_Liu
 *@create: 2021-04-17 21:16
 */
@Controller
public class UserController {

	@RequestMapping("/showUsers")
	public  String  showUser(){
       String str=null;
       str.length();
       return "index";

	}

	@RequestMapping("/showUsers2")
	public  String  showUser2(){
		int a=10/0;
		return "index";

	}

}
ExceptionApplication
package com.alan.exception;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExceptionApplication {

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

}

ArithmeticExceptionError.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>错误提示页面java.lang.ArithmeticException</title>
</head>
<body>
   <hr />
   <br>
   <br>
   <br>
   出错了,请于管理员联系。
   XXXXXX@XX.COM.CN
   <br>
   <br>
   <br>
   <br>
   <!--/*@thymesVar id="exception" type=""*/-->
   <span  th:text="${error}"> </span>
   <br>
   <br>
   <hr/>
</body>
</html>

error.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>错误提示页面</title>
</head>
<body>
   <hr />
   <br>
   <br>
   <br>
   出错了,请于管理员联系。
   XXXXXX@XX.COM.CN
   <br>
   <br>
   <br>
   <br>
   <!--/*@thymesVar id="exception" type=""*/-->
   <span  th:text="${exception}"> </span>
   <br>
   <br>
   <hr/>
</body>
</html>


index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>

nullPointerExceptionError.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>错误提示页面java.lang.NullPointerException</title>
</head>
<body>
   <hr />
   <br>
   <br>
   <br>
   出错了,请于管理员联系。
   XXXXXX@XX.COM.CN
   <br>
   <br>
   <br>
   <br>
   <!--/*@thymesVar id="exception" type=""*/-->
   <span  th:text="${error}"> </span>
   <br>
   <br>
   <hr/>
</body>
</html>

application.properties

image














     4:配置SimpleMappingExceptionResolver 处理 异常

1: 代码结构

image


2:查看执行效果

image

image


image


3:展示源代码

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.Alan</groupId>
    <artifactId>exception</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>exception</name>
    <description>Springboot Exception</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
UserController
package com.alan.exception.controller;
/**
 * @author Alan_liu
 * @Create 2021-04-17 21:16
 * @PROJECT_NAME SpringBootException3
 * @PACKAGE_NAME com.alan.exception.controller
 * @FILE_NAME null.java
 */

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *@program: SpringBootException3
 *@description:
 *@author: Alan_Liu
 *@create: 2021-04-17 21:16
 */
@Controller
public class UserController {

	@RequestMapping("/showUsers")
	public  String  showUser(){
       String str=null;
       str.length();
       return "index";

	}

	@RequestMapping("/showUsers2")
	public  String  showUser2(){
		int a=10/0;
		return "index";

	}

}
GlobalException
package com.alan.exception.exception;
/**
 * @author Alan_liu
 * @Create 2021-04-17 22:00
 * @PROJECT_NAME SpringBootException4
 * @PACKAGE_NAME com.alan.exception.controller
 * @FILE_NAME null.java
 */

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import java.util.Properties;

/**
 * 通过SimpleMappingExceptionResolver创建全局异常处理类
 *@program: SpringBootException4
 *@description:
 *@author: Alan_Liu
 *@create: 2021-04-17 22:00
 */
@Configuration
public class GlobalException {

	 /***
	  * 该方法必须有返回值。返回值类型必须是:SimpleMappingExceptionResolver
	  *
	  *
	  *@Param: []
	  *@return
	  *@throws
	  *@author Alan_Liu
	  *@date   2021/4/17 22:04
	  *
	  **/
	@Bean
	 public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){

		SimpleMappingExceptionResolver resolver =new SimpleMappingExceptionResolver();
		Properties mappings=new Properties();
		/**
		 * 参数一:异常的类型:注意必须是异常类型的全名称
		 * 参数二:视图名称
		 */
		mappings.put("java.lang.ArithmeticException","ArithmeticExceptionError");
		mappings.put("java.lang.NullPointerException","nullPointerExceptionError");
		//设置异常与视图映射信息的
		resolver.setExceptionMappings(mappings);
		return resolver;
	 }

}
ExceptionApplication
package com.alan.exception;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExceptionApplication {

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

}

ArithmeticExceptionError.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>错误提示页面java.lang.ArithmeticException</title>
</head>
<body>
   <hr />
   <br>
   <br>
   <br>
   出错了,请于管理员联系。
   XXXXXX@XX.COM.CN
   <br>
   <br>
   <br>
   <br>
   <!--/*@thymesVar id="exception" type=""*/-->
   <span  th:text="${error}"> </span>
   <br>
   <br>
   <hr/>
</body>
</html>

error.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>错误提示页面</title>
</head>
<body>
   <hr />
   <br>
   <br>
   <br>
   出错了,请于管理员联系。
   XXXXXX@XX.COM.CN
   <br>
   <br>
   <br>
   <br>
   <!--/*@thymesVar id="exception" type=""*/-->
   <span  th:text="${exception}"> </span>
   <br>
   <br>
   <hr/>
</body>
</html>


index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>

nullPointerExceptionError.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>错误提示页面java.lang.NullPointerException</title>
</head>
<body>
   <hr />
   <br>
   <br>
   <br>
   出错了,请于管理员联系。
   XXXXXX@XX.COM.CN
   <br>
   <br>
   <br>
   <br>
   <!--/*@thymesVar id="exception" type=""*/-->
   <span  th:text="${error}"> </span>
   <br>
   <br>
   <hr/>
</body>
</html>

application.properties

image










     5:自定义HandlerExceptionResolver 处理异常

image


2:查看执行效果

image

image


image


3:展示源代码

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.Alan</groupId>
    <artifactId>exception</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>exception</name>
    <description>Springboot Exception</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
UserController
package com.alan.exception.controller;
/**
 * @author Alan_liu
 * @Create 2021-04-17 21:16
 * @PROJECT_NAME SpringBootException3
 * @PACKAGE_NAME com.alan.exception.controller
 * @FILE_NAME null.java
 */

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *@program: SpringBootException3
 *@description:
 *@author: Alan_Liu
 *@create: 2021-04-17 21:16
 */
@Controller
public class UserController {

	@RequestMapping("/showUsers")
	public  String  showUser(){
       String str=null;
       str.length();
       return "index";

	}

	@RequestMapping("/showUsers2")
	public  String  showUser2(){
		int a=10/0;
		return "index";

	}

}
GlobalException
package com.alan.exception.exception;
/**
 * @author Alan_liu
 * @Create 2021-04-17 22:00
 * @PROJECT_NAME SpringBootException4
 * @PACKAGE_NAME com.alan.exception.controller
 * @FILE_NAME
 */

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

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Properties;

 /***
  *
  *@author Alan_Liu
  *@date   2021/4/17 23:01
  *
  **/
@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("ArithmeticExceptionError");
         }

		 if(ex instanceof NullPointerException){
			 mv.setViewName("nullPointerExceptionError");
		 }
		 mv.addObject("error",ex.toString());
		 return mv;
	 }
 }
ExceptionApplication
package com.alan.exception;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ExceptionApplication {

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

}

ArithmeticExceptionError.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>错误提示页面java.lang.ArithmeticException</title>
</head>
<body>
   <hr />
   <br>
   <br>
   <br>
   出错了,请于管理员联系。
   XXXXXX@XX.COM.CN
   <br>
   <br>
   <br>
   <br>
   <!--/*@thymesVar id="exception" type=""*/-->
   <span  th:text="${error}"> </span>
   <br>
   <br>
   <hr/>
</body>
</html>

error.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>错误提示页面</title>
</head>
<body>
   <hr />
   <br>
   <br>
   <br>
   出错了,请于管理员联系。
   XXXXXX@XX.COM.CN
   <br>
   <br>
   <br>
   <br>
   <!--/*@thymesVar id="exception" type=""*/-->
   <span  th:text="${exception}"> </span>
   <br>
   <br>
   <hr/>
</body>
</html>


index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>

nullPointerExceptionError.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>错误提示页面java.lang.NullPointerException</title>
</head>
<body>
   <hr />
   <br>
   <br>
   <br>
   出错了,请于管理员联系。
   XXXXXX@XX.COM.CN
   <br>
   <br>
   <br>
   <br>
   <!--/*@thymesVar id="exception" type=""*/-->
   <span  th:text="${error}"> </span>
   <br>
   <br>
   <hr/>
</body>
</html>

application.properties

image









二: springboot 整合 junit 单元测试


image

UserDaoImpl

package com.alan.exception.Service.Impl;
/**
 * @author Alan_liu
 * @Create 2021-04-17 23:27
 * @PROJECT_NAME SpringBootException5
 * @PACKAGE_NAME com.alan.exception.Service.Impl
 * @FILE_NAME null.java
 */

import org.springframework.stereotype.Repository;

/**
 *@program: SpringBootException5
 *@description:
 *@author: Alan_Liu
 *@create: 2021-04-17 23:27
 */
@Repository
public class UserDaoImpl {

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



}


UserServiceImpl
package com.alan.exception.Service;
/**
 * @author Alan_liu
 * @Create 2021-04-17 23:22
 * @PROJECT_NAME SpringBootException5
 * @PACKAGE_NAME com.alan.exception.Service
 * @FILE_NAME null.java
 */

import com.alan.exception.Service.Impl.UserDaoImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *@program: SpringBootException5
 *@description:
 *@author: Alan_Liu
 *@create: 2021-04-17 23:22
 */
@Service
public class UserServiceImpl {
   @Autowired
   private UserDaoImpl userDaoImpl;

   public void addUser(){
   	  this.userDaoImpl.saveUser();
   }
}
ExceptionApplication
package com.alan.exception;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author Alan_Liu
 */
@SpringBootApplication
public class ExceptionApplication {

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

}


UserServiceTest

package com.alan.exception;
/**
 * @author Alan_liu
 * @Create 2021-04-18 21:09
 * @PROJECT_NAME SpringBootException5
 * @PACKAGE_NAME com.alan.exception
 * @FILE_NAME null.java
 */

import com.alan.exception.Service.UserServiceImpl;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Springboot 测试类
 * @RunWith :启动器
 *   SpringJUnit4ClassRunner.class :让junit 与spring环境进行整合
 *
 * @springbootTest(classes={ExceptionApplication.class}) 1:当前类为springboot的测试类
 *                                                       2:加载springboot启动类。启动springboot
 *
 * junit 与 spring 整合 @Contextconfiguartion("classpath:applicationContext.xml")
 *@program: SpringBootException5
 *@description:
 *@author: Alan_Liu
 *@create: 2021-04-18 21:09
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {ExceptionApplication.class})  /***启动类的class**/
public class UserServiceTest {
     @Autowired
	 private UserServiceImpl userService;
	  @Test
	 public void testAddUser(){
           this.userService.addUser();
	  }

}

pom.xml

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.Alan</groupId>
    <artifactId>exception</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>exception</name>
    <description>SpringBootException</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>











posted @ 2021-04-16 22:19  一品堂.技术学习笔记  阅读(190)  评论(0编辑  收藏  举报