SpringBoot ControllerAdvice

在Spring3.2中新增了@ControllerAdvice注解,可用于定义@ExceptionHandler @ModelAttribute @InitBinder,并应用到所有被@RequestMapping注解的方法中。

示例,全局异常捕获处理:

// 编写@ControllerAdvice全局异常处理类
@ControllerAdvice
public class ExceptionHandle {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e) {
        return ResultUtil.error(100, e.getMessage());
    }
}
     // 抛出Exception异常
    @GetMapping(value = "girls/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception{
        girlService.getAge(id);
    }
原文地址:https://www.cnblogs.com/vincenshen/p/10427886.html