結(jié)合@ExceptionHandler做全局異常處理
結(jié)合@ModelAttribute做請求controller之前的操作
結(jié)合@Initbinder注解,實現(xiàn)自定義請求參數(shù)格式的綁定
@ControllerAdivce什么時候其作用,底層實現(xiàn)看這篇文章
常用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);? ? }