参考:Java 项目中的全局异常处理

    1. package com.tj.reggie.controller.utils;
    2. import lombok.extern.slf4j.Slf4j;
    3. import org.springframework.stereotype.Controller;
    4. import org.springframework.web.bind.annotation.ControllerAdvice;
    5. import org.springframework.web.bind.annotation.ExceptionHandler;
    6. import org.springframework.web.bind.annotation.ResponseBody;
    7. import org.springframework.web.bind.annotation.RestController;
    8. import java.sql.SQLIntegrityConstraintViolationException;
    9. /**
    10. * API请求全局异常处理,@RestController,@Controller注解的请求会进行的异常处理
    11. */
    12. @ControllerAdvice(annotations = {RestController.class, Controller.class})
    13. @ResponseBody
    14. @Slf4j
    15. public class ControllerException {
    16. /**
    17. * 异常处理方法
    18. *SQLIntegrityConstraintViolationException
    19. * @return
    20. */
    21. @ExceptionHandler(Exception.class)
    22. public R<String> exceptionHandler(Exception ex) {
    23. String message = ex.getMessage(); //异常信息内容
    24. log.error(message);
    25. return R.error(message);
    26. }
    27. }