SpringBoot中@RestControllerAdvice注解的使用
更新時(shí)間:2024年01月19日 09:05:03 作者:景慶197
這篇文章主要介紹了SpringBoot中@RestControllerAdvice注解的使用,@RestControllerAdvice主要用精簡(jiǎn)客戶端返回異常,它可以捕獲各種異常,需要的朋友可以參考下
1.主要作用
@RestControllerAdvice主要用精簡(jiǎn)客戶端返回異常,它可以捕獲各種異常
2.判斷異常的類型
- 后端數(shù)據(jù)校驗(yàn)異常
- 未授權(quán)異常
- 自定義異常
- 普通異常
3.實(shí)現(xiàn)
未優(yōu)化前
import com.qing.emos.wx.exception.EmosException; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.authz.UnauthorizedException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.*; @Slf4j //@RestControllerAdvice可以捕獲SpringMVC異常 @RestControllerAdvice public class ExceptionAdvice { @ResponseBody @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // ExceptionHandler用于全局捕獲異常 @ExceptionHandler(Exception.class) public String validExcepionHandler(Exception e){ log.error("執(zhí)行異常",e); // 后端驗(yàn)證失敗的異常,參數(shù)沒傳,或者傳的不對(duì) if(e instanceof MethodArgumentNotValidException){ MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e; return exception.getBindingResult().getFieldError().getDefaultMessage(); } // 精簡(jiǎn)異常的內(nèi)容,EmosException為自己定義異常 else if(e instanceof EmosException){ EmosException exception = (EmosException) e; return exception.getMsg(); } // 未授權(quán)異常 else if(e instanceof UnauthorizedException){ return "你不具備相關(guān)權(quán)限"; } // 普通異常 else { return "后端執(zhí)行異常"; } } }
優(yōu)化后
到此這篇關(guān)于SpringBoot中@RestControllerAdvice注解的使用的文章就介紹到這了,更多相關(guān)SpringBoot的@RestControllerAdvice內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java實(shí)現(xiàn)選擇排序算法的實(shí)例教程
這篇文章主要介紹了Java實(shí)現(xiàn)選擇排序算法的實(shí)例教程,選擇排序的時(shí)間復(fù)雜度為О(n²),需要的朋友可以參考下2016-05-05使用maven實(shí)現(xiàn)redis與idea的連接問題
這篇文章主要介紹了使用maven實(shí)現(xiàn)redis與idea的連接問題,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-07-07