當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
学习Spring Boot:(九)统一异常处理
生活随笔
收集整理的這篇文章主要介紹了
学习Spring Boot:(九)统一异常处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
開發的時候,每個controller的接口都需要進行捕捉異常的處理,以前有的是用切面做的,但是SpringMVC中就自帶了@ControllerAdvice ,用來定義統一異常處理類,在 SpringBoot 中額外增加了 @RestControllerAdvice。
使用
創建全局異常處理類
通過使用 @ControllerAdvice 或者 @RestControllerAdvice 定義統一的異常處理類。
在方法的注解上加上 @ExceptionHandler 用來指定這個方法用來處理哪種異常類型,然后處理完異常,將相關的結果返回。
@RestControllerAdvice public class ExceptionHandler {/*** logger*/private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandler.class);/*** 處理系統自定義的異常** @param e 異常* @return 狀態碼和錯誤信息*/@org.springframework.web.bind.annotation.ExceptionHandler(KCException.class)public ResponseEntity<String> handleKCException(KCException e) {LOGGER.error(e.getMessage(), e);return ResponseEntity.status(e.getCode()).body(e.getMessage());}@org.springframework.web.bind.annotation.ExceptionHandler(DuplicateKeyException.class)public ResponseEntity<String> handleDuplicateKeyException(DuplicateKeyException e) {LOGGER.error(e.getMessage(), e);return ResponseEntity.status(HttpStatus.CONFLICT).body("數據庫中已存在該記錄");}@org.springframework.web.bind.annotation.ExceptionHandler(AuthorizationException.class)public ResponseEntity<String> handleAuthorizationException(AuthorizationException e) {LOGGER.error(e.getMessage(), e);return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("沒有權限,請聯系管理員授權");}/*** 處理異常** @param e 異常* @return 狀態碼*/@org.springframework.web.bind.annotation.ExceptionHandler(Exception.class)public ResponseEntity<String> handleException(Exception e) {LOGGER.error(e.getMessage(), e);return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();} }測試
我在 controller 寫了一個新增的方法,由于我的數據庫中設置了 username 字段唯一索引,所以相同的值添加第二次的時候,肯定會拋出上面方法中的第二個異常 DuplicateKeyException :
@PostMapping()public ResponseEntity insert(@RequestBody SysUserEntity user) {sysUserService.save(user);return ResponseEntity.status(CREATED).build();}第一次新增的時候:
第二次新增的時候返回異常信息:
總結
以上是生活随笔為你收集整理的学习Spring Boot:(九)统一异常处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 兴业银行与第四范式开启AI平台加速模式
- 下一篇: 学习Spring Boot:(十四)sp