目录
注解
@RestControllerAdvice
RestControllerAdvice = ControllerAdvice + ResponseBody 支持json返回
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @ControllerAdvice @ResponseBody public @interface RestControllerAdvice { @AliasFor( annotation = ControllerAdvice.class ) String[] value() default {}; @AliasFor( annotation = ControllerAdvice.class ) String[] basePackages() default {}; @AliasFor( annotation = ControllerAdvice.class ) Class<?>[] basePackageClasses() default {}; @AliasFor( annotation = ControllerAdvice.class ) Class<?>[] assignableTypes() default {}; @AliasFor( annotation = ControllerAdvice.class ) Class<? extends Annotation>[] annotations() default {}; }
@ControllerAdvice
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Component public @interface ControllerAdvice { @AliasFor("basePackages") String[] value() default {}; @AliasFor("value") String[] basePackages() default {}; Class<?>[] basePackageClasses() default {}; Class<?>[] assignableTypes() default {}; Class<? extends Annotation>[] annotations() default {}; }
说明
- 支持annotations(),basePackageClasses(), basePackages()或它的别名value() 可以被指定,以限定控制器,以协助的特定子集。当应用多个选择器时,应用OR逻辑 - 意味着所选的控制器应匹配至少一个选择器
- 一般可定义@ExceptionHandler, @InitBinder 和 @ModelAttribute 适用用于所有@RequestMapping方法的方法
全局处理实践
@Slf4j @RestControllerAdvice public class GlobalExceptionHandler { /** * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器 * * @param binder */ @InitBinder public void initBinder(WebDataBinder binder) { log.info("binder.getFieldDefaultPrefix {}",binder.getFieldDefaultPrefix()); log.info("binder.getFieldMarkerPrefix {}",binder.getFieldMarkerPrefix()); } /** * 把值绑定到Model中,使全局@RequestMapping可以获取到该值 * @param model */ @ModelAttribute public void addAttributes(Model model) { model.addAttribute("key", "value"); } /** * Description : 全局异常捕捉处理 * @param ex * @return */ @ExceptionHandler(BizException.class) public R bizException(BizException ex) { log.error("bizException 异常抛出:{}", ex); return R.fail(ex); } }
当启动应用后,被 @ExceptionHandler、@InitBinder、@ModelAttribute 注解的方法,都会作用在 @RequestMapping 注解的方法上
自定义异常
@Data @AllArgsConstructor @Accessors(chain = true) public class BizException extends RuntimeException { /** * 状态码 */ protected int code; /** * 返回信息 */ protected String msg; }
Controller层处理
@GetMapping("test") public R test(@RequestParam Integer id) { if (id == null) { throw new BizException("id不能为空!"); } return R.success(id); }
此时异常会被拦截,返回自定义异常结果
{ "msg": "success", "code": 500, "success": false, "message": "id不能为空!" }
思考
由这种运用面向切面的思想,可自定义切片来整体解决一些业务上问题。如自定义校验、自定义日志、自定义事务等