GlobalExceptionHandler.java 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. package cn.seecoder.ai.exception;
  2. import cn.seecoder.ai.controller.response.ErrorRes;
  3. import cn.seecoder.ai.controller.response.Response;
  4. import lombok.extern.slf4j.Slf4j;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.validation.BindingResult;
  7. import org.springframework.validation.FieldError;
  8. import org.springframework.web.bind.MethodArgumentNotValidException;
  9. import org.springframework.web.bind.annotation.ControllerAdvice;
  10. import org.springframework.web.bind.annotation.ExceptionHandler;
  11. import org.springframework.web.bind.annotation.ResponseStatus;
  12. /**
  13. * 全局异常处理器
  14. * RuntimeException可以直接上抛出的,在此处被捕获
  15. * @author fanyanpeng
  16. * @date 2023/3/24 2:49
  17. */
  18. @Slf4j
  19. @ControllerAdvice
  20. public class GlobalExceptionHandler {
  21. @ExceptionHandler(value = IllegalArgumentException.class)
  22. @ResponseStatus(HttpStatus.BAD_REQUEST)
  23. public Response handleValidException(MethodArgumentNotValidException e) {
  24. BindingResult bindingResult = e.getBindingResult();
  25. String message = null;
  26. if (bindingResult.hasErrors()) {
  27. FieldError fieldError = bindingResult.getFieldError();
  28. if (fieldError != null) {
  29. message = fieldError.getField()+fieldError.getDefaultMessage();
  30. }
  31. }
  32. return new ErrorRes(200,message);
  33. }
  34. }