GlobalException.java 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package com.cslg.ppa.common.exception;
  2. import cn.dev33.satoken.exception.NotLoginException;
  3. import com.cslg.ppa.common.core.auth.Response;
  4. import com.cslg.ppa.common.core.auth.ResponseEnum;
  5. import jakarta.servlet.http.HttpServletRequest;
  6. import jakarta.servlet.http.HttpServletResponse;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.apache.commons.lang3.StringUtils;
  9. import org.springframework.web.bind.annotation.ExceptionHandler;
  10. import org.springframework.web.bind.annotation.RestControllerAdvice;
  11. /**
  12. * 全局异常处理
  13. */
  14. @Slf4j
  15. @RestControllerAdvice // 可指定包前缀,比如:(basePackages = "com.pj.admin")
  16. public class GlobalException {
  17. // 全局异常拦截(拦截项目中的所有异常)
  18. @ExceptionHandler
  19. public String handlerException(Exception e, HttpServletRequest request, HttpServletResponse response) throws Exception {
  20. // 打印堆栈,以供调试
  21. e.printStackTrace();
  22. if (e instanceof NotLoginException) {
  23. return Response.error(ResponseEnum.UNAUTHORIZED);
  24. } else {
  25. return Response.error(e.getMessage());
  26. }
  27. }
  28. //小世异常
  29. @ExceptionHandler
  30. public String handlerXiaoShiException(XiaoShiException e) {
  31. log.info("全局异常处理机制捕获到XiaoShiException,异常信息提示为:{}", e.getErrorCode() + "--" + e.getMessage());
  32. if (StringUtils.isNotEmpty(e.getErrorCode())) {
  33. return Response.error(Integer.parseInt(e.getErrorCode()), e.getErrorMessage());
  34. } else {
  35. return Response.error(e.getMessage());
  36. }
  37. }
  38. }