package vc.thinker.exception; import org.springframework.http.HttpStatus; import org.springframework.validation.BindException; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestControllerAdvice; import vc.thinker.response.AbstractResponse; import vc.thinker.response.SimpleResponse; import java.util.List; /** * @author : xieshaojun * @date : 2023/1/3 15:21 */ @RestControllerAdvice(annotations = RestController.class) public class ExceptionAdvice { @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class}) public AbstractResponse handleBodyValidException(MethodArgumentNotValidException e) { AbstractResponse errorResponse = new SimpleResponse(); List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors(); errorResponse.setErrorInfo(HttpStatus.BAD_REQUEST.value(), fieldErrors.get(0).getDefaultMessage()); return errorResponse; } }