GlobalExceptionHandler.java 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package com.fdkankan.common.exception;
  2. import cn.hutool.core.exceptions.ExceptionUtil;
  3. import com.fdkankan.common.constant.ServerCode;
  4. import com.fdkankan.common.exception.BusinessException;
  5. import com.fdkankan.common.response.ResultData;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.web.bind.annotation.ControllerAdvice;
  8. import org.springframework.web.bind.annotation.ExceptionHandler;
  9. import org.springframework.web.bind.annotation.ResponseBody;
  10. import javax.servlet.http.HttpServletRequest;
  11. /**
  12. * 全局异常处理器
  13. */
  14. @ControllerAdvice
  15. @Slf4j
  16. public class GlobalExceptionHandler {
  17. /**
  18. * 处理未知异常
  19. */
  20. @ResponseBody
  21. @ExceptionHandler(value = Exception.class)
  22. public ResultData exceptionHandler(HttpServletRequest httpServletRequest, Exception e) {
  23. log.error("服务错误:", e);
  24. return ResultData.error(ServerCode.SYSTEM_ERROR.code(), ExceptionUtil.stacktraceToString(e, 3000));
  25. }
  26. /**
  27. * 处理业务异常
  28. */
  29. @ResponseBody
  30. @ExceptionHandler(value = BusinessException.class)
  31. public ResultData businessExceptionHandler(HttpServletRequest httpServletRequest, BusinessException e) {
  32. log.info("业务异常code:" + e.getCode() + "msg:" + e.getMessage());
  33. return ResultData.error(e.getCode(), e.getMessage());
  34. }
  35. }