SpringBoot exception handling and unit testing

I. Exception handling in SpringBoot

1 SpringBook provides five ways to handle exceptions

1.1 Custom Error Page

SpringBoot default exception handling mechanism: SpringBoot default has provided a set of exception handling mechanism. Once an exception occurs in the program, SpringBoot sends a request like / error's url. In SpringBook, a basic Exception Controller is provided to process / error requests, and then jump to the page that displays the exception by default to display the exception information.

If we need to jump all exceptions to a custom error page, we need to create an error.html page in the src/main/resources/templates directory. Note: The name must be error

<!DOCTYPE html>
<html>
<head>
        <meta charset="UTF-8">
        <title>Error prompt page</title>
</head>
<body>
//Wrong, please contact the administrator...
<span th:text="${exception}"></span>
</body>
</html>

1.2@ExceptionHandler annotation handles exceptions

            1.2.1 Controller

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;

/**
 * SpringBoot Handling exceptions: Customizing error pages
 *
 *
 */
@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
     * This method needs to return a Model AndView: the purpose is to enable us to encapsulate exception information and view
     Designation of Graphs
     * Parametric Exception: Injects exception-producing objects into methods
     */
    @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
     * This method needs to return a Model AndView: the purpose is to enable us to encapsulate exception information and view
     Designation of Graphs
     * Parametric Exception: Injects exception-producing objects into methods
     */
    @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 page

<!DOCTYPE html>
<html>
<head>
        <meta charset="UTF-8">
        <title>Error prompt page-ArithmeticException</title>
</head>
<body>
//Wrong, please contact the administrator...
<span th:text="${error}"></span>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
        <meta charset="UTF-8">
        <title>Error prompt page-NullPointerException</title>
</head>
<body>
//Wrong, please contact the administrator...
<span th:text="${error}"></span>
</body>
</html>

1.3@Controller Advice+@ExceptionHandler annotation handles exceptions

1.3.1 needs to create a global exception class that can handle exceptions. You need to add the @Controller Advice annotation on this class

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
/**
 * Global exception handling class
 *
 *
 */
@ControllerAdvice
public class GlobalException {
    /**
     * java.lang.ArithmeticException
     * This method needs to return a Model AndView: the purpose is to enable us to encapsulate exception information and view
     Designation of Graphs
     * Parametric Exception: Injects exception-producing objects into methods
     */
    @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
     * This method needs to return a Model AndView: the purpose is to enable us to encapsulate exception information and view
     Designation of Graphs
     * Parametric Exception: Injects exception-producing objects into methods
     */
    @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 Configure SimpleMapping Exception Resolver to handle exceptions

1.4.1 Adding a method to the global exception class to complete the same exception handling

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

/**
 * Global exception handling through SimpleMapping Exception Resolver
 *
 *
 */
@Configuration
public class GlobalException {
    /**
     * This method must have a return value. The return value type must be: SimpleMapping Exception Resolver
     */
    @Bean
    public SimpleMappingExceptionResolver
    getSimpleMappingExceptionResolver(){
        SimpleMappingExceptionResolver resolver = new
                SimpleMappingExceptionResolver();
        Properties mappings = new Properties();
/**
 * Parametric 1: Type of exception, note that it must be the full name of the exception type
 * Parametric 2: View name
 */
        mappings.put("java.lang.ArithmeticException", "error1");
        mappings.put("java.lang.NullPointerException","error2");
//Setting exception and view mapping information
        resolver.setExceptionMappings(mappings);
        return resolver;
    }
}

1.5 Custom HandlerExceptionResolver Class Handles Exceptions

1.5.1 Need to implement Handler Exception Resolver interface in global exception handling class

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

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

/**
 * Global exception handling by implementing Handler Exception Resolver interface
 *
 *
 */
@Configuration
public class GlobalException implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request,
                                         HttpServletResponse response, Object handler,
                                         Exception ex) {
        ModelAndView mv = new ModelAndView();
//Judge different types of anomalies and make different view jumps
        if(ex instanceof ArithmeticException){
            mv.setViewName("error1");
        }
        if(ex instanceof NullPointerException){
            mv.setViewName("error2");
        }
        mv.addObject("error", ex.toString());
        return mv;
    }
}

2. Spring Boot Integration Junit Unit Testing

1 Create a project

2 Modify the pom file

<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
http://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>1.5.10.RELEASE</version>
        </parent>
        <groupId>com.bjsxt</groupId>
        <artifactId>19-spring-boot-test</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <properties>
                <java.version>1.7</java.version>
        </properties>
        <dependencies>
                <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-web</artifactId>
                </dependency>
                <!-- Add to junit Environmental jar package -->
                <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-test</artifactId>
                </dependency>
        </dependencies>
</project>

3 Writing business code

    3.1 Dao

import org.springframework.stereotype.Repository;

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

3.2 Business Layer

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

3.3 Writing Startup Class

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

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

4 Use SpringBoot to integrate Junit for unit testing

4.1 Writing test classes

import org.springframework.beans.factory.annotation.Autowired;

/**
 * SpringBoot Test class
 *@RunWith:starter
 *SpringJUnit4ClassRunner.class: Integrate junit with spring environment
 *
 *@SpringBootTest(classes={App.class}) 1,The current class is the springBook test class
 *@SpringBootTest(classes={App.class}) 2,Load the SpringBoot startup class. start-up
springBoot
 *
 *junit Integration with 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();
    }
}

 

Tags: Java SpringBoot Spring Junit

Posted on Wed, 02 Oct 2019 07:38:12 -0400 by Chad11