GlobalExceptionHandler.java 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package com.fdkankan.manage.exception;
  2. import com.fdkankan.manage.common.ResultCode;
  3. import com.fdkankan.manage.common.ResultData;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.dao.DataIntegrityViolationException;
  6. import org.springframework.web.bind.annotation.ExceptionHandler;
  7. import org.springframework.web.bind.annotation.ResponseBody;
  8. import org.springframework.web.bind.annotation.RestControllerAdvice;
  9. import java.util.Objects;
  10. /**
  11. * 全局异常处理器
  12. */
  13. @RestControllerAdvice
  14. @Slf4j
  15. public class GlobalExceptionHandler {
  16. /**
  17. * 处理未知异常
  18. */
  19. @ResponseBody
  20. @ExceptionHandler(value = Exception.class)
  21. public ResultData exceptionHandler(Exception e) throws Exception {
  22. log.error("服务错误:", e);
  23. return ResultData.error( 500, e.getCause().getMessage());
  24. }
  25. /**
  26. * 处理业务异常
  27. */
  28. @ResponseBody
  29. @ExceptionHandler(value = BusinessException.class)
  30. public ResultData businessExceptionHandler(BusinessException e) {
  31. log.info("业务异常code:{},message:{}", e.getCode(), e.getMessage());
  32. return ResultData.error(e.getCode(), e.getMessage());
  33. }
  34. /**
  35. * 处理业务异常
  36. */
  37. @ResponseBody
  38. @ExceptionHandler(value = DataIntegrityViolationException.class)
  39. public ResultData DataIntegrityViolationExceptionHandler(DataIntegrityViolationException e) {
  40. log.error("mysql服务错误:", e);
  41. if(e.getCause().getMessage().contains("Data too long")){
  42. return ResultData.error(ResultCode.DATA_TOO_LONG);
  43. }
  44. return ResultData.error( 500, e.getCause().getMessage());
  45. }
  46. }