GlobalExceptionHandler.java 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package com.example.handler;
  2. import com.example.exception.BaseException;
  3. import com.example.constant.MessageConstant;
  4. import com.example.exception.BaseException;
  5. import com.example.result.Result;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.web.bind.annotation.ExceptionHandler;
  8. import org.springframework.web.bind.annotation.RestControllerAdvice;
  9. import java.sql.SQLIntegrityConstraintViolationException;
  10. /**
  11. * 全局异常处理器,处理项目中抛出的业务异常
  12. */
  13. @RestControllerAdvice
  14. @Slf4j
  15. public class GlobalExceptionHandler {
  16. /**
  17. * 捕获业务异常
  18. * @param ex
  19. * @return
  20. */
  21. @ExceptionHandler
  22. public Result exceptionHandler(BaseException ex){
  23. log.error("异常信息:{}", ex.getMessage());
  24. return Result.error(ex.getMessage());
  25. }
  26. //处理SQL异常
  27. @ExceptionHandler
  28. public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
  29. // Duplicate entry '2532478980' for key 'employee.idx_username'
  30. String message = ex.getMessage();
  31. if(message.contains("Duplicate entry")){
  32. String[] split = message.split(" ");
  33. String username = split[2];
  34. String msg = username + MessageConstant.ALREADY_EXISTS;
  35. return Result.error(msg);
  36. }else {
  37. return Result.error(MessageConstant.UNKNOWN_ERROR);
  38. }
  39. }
  40. }