我正在开发基于Spring Boot的REST API。我正在使用自定义ConstraintValidator注释验证输入实体。我的问题是我无法在响应中返回ConstraintViolationException消息。我的异常处理程序无法捕获异常(可能是因为异常处理包装在其他类型的异常中)。
请问我如何处理此问题的建议?
我已经在Internet上进行了搜索,但找不到适合我的解决方案,而且这样做也浪费了我几个小时。
示例注释:
@Documented
@Retention(RUNTIME)
@Target({FIELD, PARAMETER})
@Constraint(validatedBy = BirthDateValidator.class)
public @interface ValidBirthDate {
String message() default "The birth date is not valid.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Validator类:
public class BirthDateValidator extends FieldValidationBase implements ConstraintValidator<ValidBirthDate, LocalDate> {
private static final Logger LOGGER = LoggerFactory.getLogger(BirthDateValidator.class);
@Override
public void initialize(ValidBirthDate constraintAnnotation) {
}
@Override
public boolean isValid(LocalDate birthDate, ConstraintValidatorContext constraintValidatorContext) {
constraintValidatorContext.disableDefaultConstraintViolation();
LOGGER.info("Starting the validation process for birth date {}.", birthDate);
if(birthDate == null) {
constraintValidatorContext.buildConstraintViolationWithTemplate("The birth date is null.")
.addConstraintViolation();
return false;
}
//other validations
return true;
}
模型类:
public class Manager extends BaseUser {
//other fields
@Valid
@ValidBirthDate
private LocalDate birthDate;
//setters & getters
异常处理程序:
@ExceptionHandler(value = ConstraintViolationException.class)
public ResponseEntity handleConstraintViolationException(ConstraintViolationException ex, WebRequest request) {
List<String> errors = new ArrayList<>();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
errors.add(violation.getRootBeanClass().getName() + ": " + violation.getMessage());
}
Error response = new Error(errors);
return new ResponseEntity<Object>(response, new HttpHeaders(), BAD_REQUEST);
}
控制器:
@RestController
@RequestMapping(value = "/register", consumes = "application/json", produces = "application/json")
public class RegistrationController {
@Autowired
private RegistrationService registrationService;
@PostMapping(value = "/manager")
public ResponseEntity registerManager(@RequestBody @Valid Manager manager) {
registrationService.executeSelfUserRegistration(manager);
return new ResponseEntity<>(new Message("User " + manager.getEmailAddress() + " registered successfully!"), CREATED);
}
}
我得到了400响应代码,但没有看到包含违反约束消息的任何响应正文。
答案 0 :(得分:0)
经过更多调试之后,我发现所有违反约束的条件都包裹在MethodArgumentNotValidException
中(由于有@Valid
注释)-我必须在该异常中进行一些挖掘才能获得我的信息。
我已经从handleMethodArgumentNotValid()
覆盖了ResponseEntityExceptionHandler
方法,这就是我要如何使用它的方法:
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
List<String> errorMessages = new ArrayList<>();
BindingResult bindingResult = ex.getBindingResult();
List<ObjectError> errors = bindingResult.getAllErrors();
for(ObjectError error : errors) {
String message = error.getDefaultMessage();
errorMessages.add(message);
}
return new ResponseEntity<>(new Error(errorMessages), new HttpHeaders(), BAD_REQUEST);
}
也许这可以帮助某人。
答案 1 :(得分:0)
当目标参数验证失败时,Spring Boot 会抛出 MethodArgumentNotValidException
异常。我已从该异常的 bindingResult
中提取错误消息,如下所示:
@RestControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
//to extract the default error message from a diagnostic
// information about the errors held in MethodArgumentNotValidException
Exception exception = new Exception(ex.getBindingResult().getAllErrors().get(0).getDefaultMessage());
return this.createResponseEntity(HttpStatus.BAD_REQUEST, exception, request);
}
private ResponseEntity<Object> createResponseEntity(
HttpStatus httpStatus, Exception ex, WebRequest request) {
ErrorResponse errorResponse = ErrorResponse.builder()
.timestamp(LocalDateTime.now())
.status(httpStatus.value())
.error(httpStatus.getReasonPhrase())
.message(ex.getMessage())
.path(request.getDescription(true))
.build();
return handleExceptionInternal(ex, errorResponse,
new HttpHeaders(), httpStatus, request);
}
}
ErrorResponse 类:
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ErrorResponse {
private LocalDateTime timestamp;
private int status;
private String error;
private String message;
private String path;
}
响应将是 400 和 JSON 格式的正文,如下所示:
{
"timestamp": "2021-01-20T10:30:15.011468",
"status": 400,
"error": "Bad Request",
"message": "Due date should not be greater than or equal to Repeat Until Date.",
"path": "uri=/api/tasks;client=172.18.0.5;user=109634489423695603526"
}
我希望这会有所帮助。如果您需要有关类级约束的详细说明,请查看 this video。