9.玩轉Spring Boot 全域性異常處理@ControllerAdvice
阿新 • • 發佈:2019-02-02
玩轉Spring Boot 全域性異常處理@ControllerAdvice
在開發中出現異常後,可能需要一個統一處理的地方,來處理程式出現的異常,針對不同的異常做不同的處理,這裡我們通過@ExceptionHandler註解來實現。在WEB開發中,比如頁面出入進來日期,需要進行一些轉換那麼這裡使用@InitBinder註解來處理。上面說的是一些使用場景,接下來具體如何實現。1.使用@ExceptionHandler當前Controller異常處理
@ExceptionHandler可以使用在任何用@Controller註解修飾的類中,設定出現某種異常的時候執行,具體程式碼如下: (1)新建Controller,名稱為:TestController,程式碼如下:package com.chengli.springboot.controller; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.context.request.WebRequest; @RestController public class TestController { @RequestMapping(value = "/") public String hello() { throw new RuntimeException(); } @ExceptionHandler(value = { RuntimeException.class }) public String exception(Exception e, WebRequest webRequest) { return "出現異常了,在本類處理"; } }
(2)新建啟動入口類,名稱:MainConfig,具體程式碼如下:
(3)執行啟動,在瀏覽器輸入後,會出現“出異常了,在本類處理”package com.chengli.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MainConfig { public static void main(String[] args) { SpringApplication.run(MainConfig.class, args); } }
2.使用@ExceptionHandler全域性異常處理
(1)新建全域性異常處理類,程式碼如下:package com.chengli.springboot.exception; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; @RestControllerAdvice public class DefaultExceptionHandlerAdvice { @ExceptionHandler(value = { Exception.class }) public String exception() { return "出異常了,全域性異常處理"; } }
(2)這裡需要提醒一點的是,優先順序問題,同一種異常處理在本類的優先順序要高,會優先使用本類的其次是全域性的。所以我們這裡需要將本類使用@ExceptionHandler的方法先註釋掉,然後在瀏覽器上輸入後,出現“出異常了,全域性異常處理”。那麼就OK啦。 注意:這裡我使用的是@RestControllerAdvice,@RestControllerAdvice是一個組合註解,組合了@ControllerAdvice、@ResponseBody,因為我這裡是演示直接返回的是內容,所以為了方便使用@RestControllerAdvice,如果你們的異常需要返回頁面啊之類的,你可以使用@ControllerAdvice分別定製。
3.使用@InitBinder註解處理繫結值
(1)新增initBinder方法,程式碼如下:@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
setValue(format.parse(text));
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}
(2)上面的程式碼我是在處理引數的時候,將日期引數按照指定格式parse後在進行設定。@initBinder註解在很多場景下能用的上,比如你要處理字串用來編碼防止XSS攻擊啊或者你要預先做個處理的都可以,這裡就不細說了,@initBinder註解是可以放在所有使用了@Controller類中的,也可以放到全域性類中,也就是說使用了@ControllerAdvice註解的類。 有興趣的朋友可以加群探討相互學習: Spring Boot QQ交流群:599546061