目录结构

image.png

代码

  1. package com.ichenshengjie.product.exception;
  2. import com.ichenshengjie.common.utils.R;
  3. import lombok.extern.slf4j.Slf4j;
  4. import org.springframework.validation.BindingResult;
  5. import org.springframework.web.bind.MethodArgumentNotValidException;
  6. import org.springframework.web.bind.annotation.ExceptionHandler;
  7. import org.springframework.web.bind.annotation.RestControllerAdvice;
  8. import java.util.HashMap;
  9. /**
  10. * 集中处理所有异常
  11. */
  12. @Slf4j
  13. @RestControllerAdvice(basePackages = "com.ichenshengjie.product.controller")
  14. public class ShanExceptionControllerAdvice {
  15. /**
  16. * 数据校验异常
  17. * 注解中的value参数代表要拦截的异常类是什么, 可以通过
  18. * log.error("数据校验发生异常{},异常类型:{}", e.getMessage(), e.getClass());
  19. * 将其打印出来
  20. * @param e
  21. * @return
  22. */
  23. @ExceptionHandler(value = MethodArgumentNotValidException.class)
  24. public R handleValidException(MethodArgumentNotValidException e) {
  25. HashMap<String, String> map = new HashMap<>();
  26. log.error("数据校验发生异常{},异常类型:{}", e.getMessage(), e.getClass());
  27. BindingResult result = e.getBindingResult();
  28. result.getFieldErrors().forEach((fieldError) -> {
  29. String message = fieldError.getDefaultMessage();
  30. String field = fieldError.getField();
  31. map.put(field, message);
  32. });
  33. return R.error(400, "提交的数据不合法").put("data", map);
  34. }
  35. /**
  36. * 所有异常
  37. * @return
  38. */
  39. @ExceptionHandler(value = Throwable.class)
  40. public R handleException(){
  41. return R.error();
  42. }
  43. }