GlobalExceptionHandler.java 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package com.fdkankan.manage_jp.exception;
  2. import com.fdkankan.manage_jp.common.ResultCode;
  3. import com.fdkankan.manage_jp.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. /**
  10. * 全局异常处理器
  11. */
  12. @RestControllerAdvice
  13. @Slf4j
  14. public class GlobalExceptionHandler {
  15. /**
  16. * 处理未知异常
  17. */
  18. @ResponseBody
  19. @ExceptionHandler(value = Exception.class)
  20. public ResultData exceptionHandler(Exception e) throws Exception {
  21. log.error("服务错误:", e);
  22. return ResultData.error( 500, e.getCause().getMessage());
  23. }
  24. /**
  25. * 处理业务异常
  26. */
  27. @ResponseBody
  28. @ExceptionHandler(value = BusinessException.class)
  29. public ResultData businessExceptionHandler(BusinessException e) {
  30. log.info("业务异常code:{},message:{}", e.getCode(), e.getMessage());
  31. return ResultData.error(e.getCode(), e.getMessage());
  32. }
  33. /**
  34. * 处理业务异常
  35. */
  36. @ResponseBody
  37. @ExceptionHandler(value = DataIntegrityViolationException.class)
  38. public ResultData DataIntegrityViolationExceptionHandler(DataIntegrityViolationException e) {
  39. log.error("mysql服务错误:", e);
  40. if(e.getCause().getMessage().contains("Data too long")){
  41. return ResultData.error(ResultCode.DATA_TOO_LONG);
  42. }
  43. return ResultData.error( 500, e.getCause().getMessage());
  44. }
  45. }