SpringBoot異常統一處理2.2.5的處理方法和exception不顯示的問題

1.自定義異常

/**
 * @Auther: DELL
 * @Date: 2020/3/12 14:00
 * @Description:
 */
public class myException extends RuntimeException {

    public myException() {
        super("用戶不在場");
    }
}

2.首先自定義處理器

   /**1..................
     * @ExceptionHandler 可以指定class如果不指定就是處理所有的
     * @param e
     * @return
     * 這種情況下游覽器和服務器返回的都是json
     */

    @ExceptionHandler(myException.class)
    public String myexcptionC(Exception e, HttpServletRequest request){
        Map<String,Object> Object=new HashMap<>();
        //必須傳入自己的錯誤狀態碼
        request.setAttribute("javax.servlet.error.status_code",500);
        Object.put("code","user don't have ");
        Object.put("message",e.getMessage());
        request.setAttribute("ext",Object);
        return "forward:/error";
    }

3.給容器中加入我們自己定義的ErrorAttributes

2.2.5版本和1.X在這裏有區別

首先如果我們不加這個構造器的話,就會顯示的時候exception爲空。

其次2.2.5這裏講RequestAttributes換成了WebRequest。

/**
 * @Auther: DELL
 * @Date: 2020/3/12 15:43
 * @Description:
 */
@Component
public class myErrorAttributes extends DefaultErrorAttributes {

    public myErrorAttributes() {
        super(true);
    }



    //返回值的map就是頁面和json能獲取的所有字段
        @Override
        public Map<String, Object> getErrorAttributes(WebRequest requestAttributes, boolean includeStackTrace) {
            Map<String, Object> map = super.getErrorAttributes( requestAttributes, includeStackTrace);
            map.put("company","atguigu");

            //我們的異常處理器攜帶的數據
            Map<String,Object> ext = (Map<String, Object>) requestAttributes.getAttribute("ext", 0);
            map.put("ext",ext);
            return map;
        }

}

 

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