@ControllerAdvice的三种用途,统一异常处理,自定义请求参数格式,执行controller方法之前执行自己的方法(做一些权限控制)

@ControllerAdvice注解是什么?

结合@ExceptionHandler做全局异常处理

结合@ModelAttribute做请求controller之前的操作

结合@Initbinder注解,实现自定义请求参数格式的绑定

@ControllerAdivce什么时候其作用,底层实现看这篇文章

@ControllerAdvice注解是什么?

常用ControllerAdvice声明一些全局性的东西

结合@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(),"内部服务异常,请联系管理员");    }/**    * 403的异常*@paramex    *@return*/@ExceptionHandler(ClientTokenException.class)@ResponseStatus(HttpStatus.FORBIDDEN)publicBaseResponseclientTokenExceptionHandler(ClientTokenException ex){        log.error(ex.getMessage(),ex);returnnewBaseResponse(ex.getStatus(), ex.getMessage());    }

结合@ModelAttribute做请求controller之前的操作

在请求controller、方法之前会先执行这个方法@ModelAttribute("loginUserInfo")publicUserDetailsmodelAttribute(){return(UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();    }

结合@Initbinder注解,实现自定义请求参数格式的绑定

// @InitBinder标注的initBinder()方法表示注册一个Date类型的类型转换器,用于将类似这样的2019-06-10//日期格式的字符串转换成Date对象@InitBinderprotectedvoidinitBinder(WebDataBinder binder){        SimpleDateFormat dateFormat =newSimpleDateFormat("yyyy-MM-dd");        dateFormat.setLenient(false);        binder.registerCustomEditor(Date.class,newCustomDateEditor(dateFormat,false));    }自动去重string前后的空格,并且将空格自动转换为null,但是如果是ResponsBody类型的请求,已经流化了,就需要另作处理。@InitBinderpublicvoidinitBinder(WebDataBinder binder){        StringTrimmerEditor trimmerEditor =newStringTrimmerEditor(true);        binder.registerCustomEditor(String.class, trimmerEditor);    }

@ControllerAdivce什么时候其作用,底层实现看这篇文章

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。