08.Spring Boot 實戰~Spring Boot異常處理和單元測試

08.Spring Boot 實戰~Spring Boot異常處理和單元測試

本文是上一篇文章的後續,詳情點擊該鏈接

        關於異常處理呢,在Spring Boot中提供了五種處理方式

自定義錯誤頁面

       在SpringBoot中已經默認的提供了一套異常處理機制。 一旦程序中出現了異常 SpringBoot 會向/error 的 url 發送請求。並且提供了一個名爲BasicErrorController 來處理/error 請求,然後跳轉到默認顯示異常的頁面來展示異常信息。

       如 果 我 們 需 要 將 所 有 的 異 常 同 一 跳 轉 到 自 定 義 的 錯 誤 頁 面 , 需 要 再 src/main/resources/templates 目錄下創建 error.html 頁面。注意:頁面名稱必須叫 error

在這裏插入圖片描述

        只要出現異常就會自動跳到error.html這裏,隨便創建一個項目,故意寫錯路徑或者故意弄錯其他東西試一下就知道了。

通過@ExceptionHandler 註解處理異常

寫在Controller裏
@Controller
@RequestMapping("/alvin")
public class MyController {

    @RequestMapping("/ShowMain")
    public String Show(){
        String str = null;
        //鐵定空指針異常,先製造一個再說.....
        str.length();
        return "main";
    }

    //空指針異常處理
    @ExceptionHandler(value = {java.lang.NullPointerException.class} )
    public ModelAndView nullpointExcepitonHandler(Exception e){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("err",e.toString());
        modelAndView.setViewName("nullpoint");
        return modelAndView;
    }

}

然後視圖頁面接收發送過來的異常信息

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>nullpoint</title>
    </head>
    <body>
        <!--/*@thymesVar id="err" type=""*/-->
        <span th:text="${err}"></span>
    </body>
</html>

在這裏插入圖片描述

通過@ControllerAdvice 與@ExceptionHandler 註解處理異常

我們先創建一個全局的異常處理類

在這裏插入圖片描述

@ControllerAdvice
public class GlobalException {
    @ExceptionHandler(value = {java.lang.NullPointerException.class} )
    public ModelAndView nullpointExcepitonHandler(Exception e){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("err",e.toString());
        modelAndView.setViewName("nullpoint");
        return modelAndView;
}

    @ExceptionHandler(value = {java.lang.ArithmeticException.class} )
    public ModelAndView arithmeticExceptionHandler(Exception e){
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("err",e.toString());
            modelAndView.setViewName("exception");
            return modelAndView;
        }
    }
然後自己製造一個算數異常比如2/0跳轉接收即可
<!DOCTYPE html>
<html lang="en"xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>exception</title>
    </head>
    <body>
        <!--/*@thymesVar id="err" type=""*/-->
        <span th:text="${err}"></span>
    </body>
</html>

通過 SimpleMappingExceptionResolver 對象處理異常

        我們在全局異常處理類當中方法數量會非常多,因爲可能會需要處理多個不同的異常,而每當多需要處理一個就要多加一個方法。這樣會導致方法太多,所以我們要只通過一個方法來處理不同的異常並跳轉不同的頁面

修改下剛纔那個類

@ControllerAdvice
public class GlobalException {
    //此方法返回值必須是SimpleMappingExceptionResolver對象
    @Bean
    public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){
        SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
        Properties properties = new Properties(); 
        //參數一:異常類型,並且是全名參數二:視圖名稱
        properties.put("java.lang.NullPointerException","nullpoint");
        properties.put("java.lang.ArithmeticException","exception");
        resolver.setExceptionMappings(properties);
        return resolver;
    }
}

通過自定義 HandlerExceptionResolver 對象處理異常

@ControllerAdvice
public class GlobalException implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        ModelAndView modelAndView = new ModelAndView();
        //判斷不同異常類型,做不同視圖的跳轉
        if(e instanceof NullPointerException){
            modelAndView.setViewName("nullpoint");
        }
        if(e instanceof ArithmeticException){
            modelAndView.setViewName("exception");
        }
        modelAndView.addObject("error",e.toString());
        return modelAndView;
    }
}

SpringBoot 整合 Junit 單元測試

在pom.xml添加啓動器
    <dependency>
      <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
          <scope>test</scope>
      <!--junit-vintage-engine 提 供 了 Junit3 與 Junit4的 運行 平 臺 -->
      <exclusions>
        <exclusion>
          <groupId>org.junit.vintage</groupId>
          <artifactId>junit-vintage-engine</artifactId>
        </exclusion>
      </exclusions>
    </dependency>
測試代碼

在這裏插入圖片描述

@SpringBootTest
public class TestProject {
    @Test
    public void Menu(){
        System.out.println("hello world");
    }
}

在這裏插入圖片描述

這個時候我們可以看到,不用Main方法也能運行

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章