@ControllerAdvice的三種用途,統(tǒng)一異常處理,自定義請求參數(shù)格式,執(zhí)行controller方法之前執(zhí)行自己的方法(做一些權(quán)限控制)

@ControllerAdvice注解是什么?

結(jié)合@ExceptionHandler做全局異常處理

結(jié)合@ModelAttribute做請求controller之前的操作

結(jié)合@Initbinder注解,實現(xiàn)自定義請求參數(shù)格式的綁定

@ControllerAdivce什么時候其作用,底層實現(xiàn)看這篇文章

@ControllerAdvice注解是什么?

常用ControllerAdvice聲明一些全局性的東西

結(jié)合@ExceptionHandler做全局異常處理

這里表示Controller拋出的MethodArgumentNotValidException異常由這個方法處理@ExceptionHandler(MethodArgumentNotValidException.class)publicResultexceptionHandler(MethodArgumentNotValidException e){? ? ? ? Result result =newResult(BizExceptionEnum.INVALID_REQ_PARAM.getErrorCode(),? ? ? ? ? ? ? ? BizExceptionEnum.INVALID_REQ_PARAM.getErrorMsg());? ? ? ? logger.error("req params error", e);returnresult;? ? }可以用來判斷不同的異常的處理方式。ps:/**? ? * 500的異常會被這個方法捕獲*/@ExceptionHandler(Exception.class)@ResponseStatus(HttpStatus.OK)publicBaseResponsehandleError(Exception ex){? ? ? ? log.error(ex.getMessage(), ex);returnnewBaseResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(),"內(nèi)部服務(wù)異常,請聯(lián)系管理員");? ? }/**? ? * 403的異常*@paramex? ? *@return*/@ExceptionHandler(ClientTokenException.class)@ResponseStatus(HttpStatus.FORBIDDEN)publicBaseResponseclientTokenExceptionHandler(ClientTokenException ex){? ? ? ? log.error(ex.getMessage(),ex);returnnewBaseResponse(ex.getStatus(), ex.getMessage());? ? }

結(jié)合@ModelAttribute做請求controller之前的操作

在請求controller、方法之前會先執(zhí)行這個方法@ModelAttribute("loginUserInfo")publicUserDetailsmodelAttribute(){return(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();? ? }

結(jié)合@Initbinder注解,實現(xiàn)自定義請求參數(shù)格式的綁定

// @InitBinder標注的initBinder()方法表示注冊一個Date類型的類型轉(zhuǎn)換器,用于將類似這樣的2019-06-10//日期格式的字符串轉(zhuǎn)換成Date對象@InitBinderprotectedvoidinitBinder(WebDataBinder binder){? ? ? ? SimpleDateFormat dateFormat =newSimpleDateFormat("yyyy-MM-dd");? ? ? ? dateFormat.setLenient(false);? ? ? ? binder.registerCustomEditor(Date.class,newCustomDateEditor(dateFormat,false));? ? }自動去重string前后的空格,并且將空格自動轉(zhuǎn)換為null,但是如果是ResponsBody類型的請求,已經(jīng)流化了,就需要另作處理。@InitBinderpublicvoidinitBinder(WebDataBinder binder){? ? ? ? StringTrimmerEditor trimmerEditor =newStringTrimmerEditor(true);? ? ? ? binder.registerCustomEditor(String.class, trimmerEditor);? ? }

@ControllerAdivce什么時候其作用,底層實現(xiàn)看這篇文章

https://zhuanlan.zhihu.com/p/73087879?from_voters_page=true

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容