参考: https://www.cnblogs.com/lenve/p/10748453.html

    @ControllerAdvice或@RestControllerAdvice作用:
    1.全局异常处理
    2.全局数据绑定
    3.全局数据预处理
    异常定义:

    1. /**
    2. * 这些状态可以参照 HttpStatus
    3. */
    4. public enum ResponseStateEnum {
    5. SUCCESS(200),
    6. PARAM_ERROR(400),
    7. TOKEN_INVALID(401),
    8. EXISTED(402),
    9. AUTH_ERROR(403),
    10. NOT_EXIST(404),
    11. SERVER_ERROR(500),
    12. EXPIRED(501);
    13. private final int state;
    14. private ResponseStateEnum(int state) {
    15. this.state = state;
    16. }
    17. public int getState() {
    18. return state;
    19. }
    20. }
    1. /**
    2. * @author gosling
    3. * @description 用于controller层抛出异常, 该异常会被拦截器自动封装成ResponseMessage对象
    4. * @update 修订描述
    5. */
    6. public class RestMessageException extends RuntimeException {
    7. private ResponseStateEnum responseStateEnum;
    8. public RestMessageException(ResponseStateEnum responseStateEnum, String message) {
    9. super(message);
    10. this.responseStateEnum = responseStateEnum;
    11. }
    12. public int getState() {
    13. return this.responseStateEnum.getState();
    14. }
    15. }

    配置示例:

    1. package top.xinzhang0618.demo.controller;
    2. import java.util.HashMap;
    3. import java.util.Map;
    4. import org.springframework.ui.Model;
    5. import org.springframework.web.bind.WebDataBinder;
    6. import org.springframework.web.bind.annotation.ExceptionHandler;
    7. import org.springframework.web.bind.annotation.InitBinder;
    8. import org.springframework.web.bind.annotation.ModelAttribute;
    9. import org.springframework.web.bind.annotation.RestControllerAdvice;
    10. import top.xinzhang0618.demo.exception.RestMessageException;
    11. /**
    12. * Controller
    13. *
    14. * @author gavin
    15. * @version 2020/6/10 0010
    16. * 使用 RestControllerAdvice 相比 ControllerAdvice 可以省去 @ResponseBody注解
    17. */
    18. @RestControllerAdvice
    19. public class Controller {
    20. /**
    21. * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
    22. */
    23. @InitBinder
    24. public void initBinder(WebDataBinder binder) {
    25. }
    26. /**
    27. * 把值绑定到Model中,使全局@RequestMapping可以获取到该值
    28. */
    29. @ModelAttribute
    30. public void addAttributes(Model model) {
    31. model.addAttribute("author", "Gavin-test");
    32. }
    33. /**
    34. * 全局异常捕捉处理
    35. */
    36. @ExceptionHandler(value = RestMessageException.class)
    37. public Map errorHandler(RestMessageException ex) {
    38. Map map = new HashMap(3);
    39. map.put("code", ex.getState());
    40. map.put("msg", ex.getMessage());
    41. return map;
    42. }
    43. }

    测试:

    1. @RequestMapping("/test")
    2. @CrossOrigin
    3. @RestController
    4. public class TestController {
    5. @GetMapping("/11")
    6. public void testException(ModelMap modelMap, @ModelAttribute("author") String author22) {
    7. String author = (String) modelMap.get("author");
    8. System.out.println(author);
    9. System.out.println("===" + author22);
    10. throw new RestMessageException(ResponseStateEnum.AUTH_ERROR, "未授权");
    11. }
    12. }
    13. -------------
    14. 控制台:
    15. Gavin-test
    16. ===Gavin-test
    17. 请求返回:{"msg":"未授权","code":403}

    碧色配置参考:

    1. /**
    2. * Author: mooner
    3. * Date: 18-12-7
    4. */
    5. @ControllerAdvice
    6. public class Controller {
    7. @Value("${system.style.host}")
    8. private String styleHost;
    9. @Value("${system.style.version}")
    10. private int styleVersion;
    11. @Value("${system.order.style.host}")
    12. private String createOrderStyleHost;
    13. @ModelAttribute
    14. public void populateModel(Model model, HttpServletRequest req) {
    15. model.addAttribute("styleHost", styleHost);
    16. model.addAttribute("styleVersion", DateTimeUtils.getIntToday() + "" + styleVersion);
    17. model.addAttribute("styleVersionNum", styleVersion);
    18. model.addAttribute("createOrderStyleHost", createOrderStyleHost);
    19. // model.addAttribute("loginUser", HTTPUtils.getSesssion(req));
    20. }
    21. @ExceptionHandler(BindException.class)
    22. public @ResponseBody
    23. String handBindException(BindException e) {
    24. return new JSONObject()
    25. .fluentPut("status", "0")
    26. .fluentPut("msg", "参数错误")
    27. .toJSONString();
    28. }
    29. @ExceptionHandler(AppException.class)
    30. public String handNotFoundException(HttpServletResponse httpServletResponse, Model model, AppException e) {
    31. httpServletResponse.setStatus(e.getState());
    32. model.addAttribute("message", e.getMessage());
    33. return "error";
    34. }
    35. }