springboot基礎篇——全域性異常處理
阿新 • • 發佈:2019-01-08
基於之前的demo:springboot基礎篇——基礎入門
專案結構
一、建立全域性異常處理類
程式碼:
package com.springboot.controller; import java.util.HashMap; import java.util.Map; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(RuntimeException.class) @ResponseBody public Map<String, Object> exceptionHandler() { Map<String, Object> map = new HashMap<String, Object>(); map.put("errorCode", "000001"); map.put("errorMsg", "系統錯誤!"); return map; } }
關鍵程式碼說明:
[email protected]
標註在類上面的額一個 @Controller 類的一個輔助類,當請求出現異常,自動跳轉到該類進行處理
[email protected](RuntimeException.class)
標註在異常處理方法上面,標註這個方法是處理什麼型別的異常的。我這裡是處理的,RuntimeException.class (執行時異常)
3.@ResponseBody
這裡是說明,方法的返回值是json格式的資料(瀏覽器請求後展示效果)。如果想進行頁面跳轉,就使用引數 model 類或modelAndView
二、手動製造執行時異常
如圖: