我有一个控制器
@PutMapping(value = "/changeEmail", consumes = MediaType.APPLICATION_JSON_VALUE)
public HttpEntity<ChangeEmailDTO> showChangeEMail(
@RequestBody @Valid ChangeEmailDTO changeEmailDTO
) {
System.out.println("Email: " + changeEmailDTO.getEmail());
return ResponseEntity.ok(changeEmailDTO);
}
如果用户提供了错误数据,则抛出MethodArgumentNotValidException异常。 我创建了一个异常处理程序
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ValidationErrorDTO processValidationError(MethodArgumentNotValidException ex) {
BindingResult result = ex.getBindingResult();
List<FieldError> fieldErrors = result.getFieldErrors();
return processFieldErrors(fieldErrors);
}
private ValidationErrorDTO processFieldErrors(List<FieldError> fieldErrors) {
ValidationErrorDTO dto = new ValidationErrorDTO();
for (FieldError fieldError: fieldErrors) {
String localizedErrorMessage = resolveLocalizedErrorMessage(fieldError);
dto.addFieldError(fieldError.getField(), localizedErrorMessage);
}
return dto;
}
private String resolveLocalizedErrorMessage(FieldError fieldError) {
Locale currentLocale = LocaleContextHolder.getLocale();
String localizedErrorMessage = messageSource.getMessage(fieldError, currentLocale);
//If the message was not found, return the most accurate field error code instead.
//You can remove this check if you prefer to get the default error message.
if (localizedErrorMessage.equals(fieldError.getDefaultMessage())) {
String[] fieldErrorCodes = fieldError.getCodes();
localizedErrorMessage = fieldErrorCodes[0];
}
return localizedErrorMessage;
}
其中一个字段已由我创建验证
@Documented
@Constraint(validatedBy = EmailValidator.class)
@Target( {ElementType.FIELD} )
@Retention(RetentionPolicy.RUNTIME)
public @interface IsValidEmail {
String message() default "Please enter a valid e-mail address.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
并替换属性文件中的默认消息
IsValidEmail.changeEmailDTO.email=Please enter a valid e-mail address.
但是,在响应中的json数据是
{"fieldErrors"[{"field":"email","message":"IsValidEmail.changeEmailDTO.email"}]}
为什么?