SpringBoot的異常處理

     如何對項目的異常進行處理,在這裏我做個總結,如果項目的異常不進行處理,就把異常信息直接拋給用戶,用戶體驗度就會很差很差,如果對異常進行處理的,還能幫助開發人員對程序的分析和解決問題提供了直觀的反饋。這就是爲什麼要對異常進行處理的原因(個人理解)

    首先,springboot默認提供了對異常的處理 有兩個地方可以存放展示給用戶看的錯誤頁面,一個是在static下,一個是在templates下,我這裏是放在templates下  如下圖所示:

                                                         

    springboot會自動捕獲404 、500等錯誤信息,會從static 和templates 查找是否有對應的404.html 或500.html 如果查找不到,springboot有一套錯誤頁面,就會將自帶的錯誤頁面響應回瀏覽器。

    這是SpringBoot最簡單的異常頁面處理,但是這樣的話 ,作爲我們開發人員來說,有些異常信息是我們意想不到的或者是這些異常不是404 或 500 ,那麼我們應該怎麼樣才能跳轉到指定的錯誤頁面呢??? 如果可以在異常頁面中可以直接查看是出現了什麼異常,調用了哪個方法,或者是訪問了什麼路徑出現的異常,那麼就不用去服務器中查看日誌文件了,於是springboot官方提供了一個解決方案,使用thymeleaf 模板在html中可以直接查看,源碼與效果如下:

  error.html  

   
  <div>
        <div th:utext="'<!--'" th:remove="tag"></div>
        <div th:utext="'Failet Request URL : ' + ${url}" th:remove="tag"></div>
        <div th:utext="'Exception message : ' + ${exception.message}" th:remove="tag"></div>
        <ul th:remove="tag">
            <li th:each="st : ${exception.stackTrace}" th:remove="tag"><span th:utext="${st}" th:remove="tag"></span></li>
        </ul>
        <div th:utext="'--$gt'" th:remove="tag"></div>
    </div>


   最終達到的目的:

        

上面是展示給用戶看的 下面是開發人員看的

    

這樣我們就可以不用去查看服務器日誌來判斷是什麼引起的異常。

 那麼我們就來看一下是怎麼實現的!

    首先我們先明確一下,404、500信息還是交給springboot默認處理方式,就是通過查找404頁面或者500頁面,其他異常我們自己處理。

    首先我們先自己定義一個異常類,繼承運行時異常類

如下:

    源碼:

package com.lf.blog;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFundException extends RuntimeException {
    public NotFundException() {
    }

    public NotFundException(String message) {
        super(message);
    }

    public NotFundException(String message, Throwable cause) {
        super(message, cause);
    }
}


    然後我們定義一個異常控制類

                                                    

源碼:

package com.lf.blog.Handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice //會攔截所有controller註解的控制器
public class ControllerExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    public ModelAndView ExceptionHandler(HttpServletRequest request,Exception e) throws Exception {
        logger.error("request URL : {}, Exception : {}",request.getRequestURI(),e);

        if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
            throw e;
        }

        ModelAndView mav = new ModelAndView();
        mav.addObject("url",request.getRequestURI());
        mav.addObject("exception",e);
        mav.setViewName("error/error");
        return mav;
    }
}


現在我們來試一下是否可行

    

然後我們來訪問頁面 這是我僞造的找不到頁面的demo


出現404 那麼這個方式是可行的,這樣的話就能對異常有一個全局可控的狀態了

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