简体   繁体   中英

Spring Boot: How to get the Serialized Name from FieldError.getField()

Is there a way getting the serialized name in an ExceptionHandler that catches MethodArgumentNotValidExceptions with the FieldError.getField() method?

(see also https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/validation/FieldError.html#getField-- )

I have my POJO with the entry

@NotNull
@JsonProperty("photo-urls")
private List<URL> photoUrls;

and this code in the ExceptionHandler :

@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
private static Error handleException(final MethodArgumentNotValidException ex, final HttpServletRequest httpRequest) {
final List<ObjectError> exceptionErrors = ex.getBindingResult().getAllErrors();

exceptionErrors.forEach((final ObjectError exceptionError) -> {
    if (exceptionError instanceof FieldError) {
        final FieldError fieldError = (FieldError) exceptionError;
        final InvalidParam invalidParam = new InvalidParam();

        invalidParam.setName(fieldError.getField());
...

and whenever this field is missing (violating the @NotNull constraint), getField() returns photoUrls instead of photo-urls . But the for client photo-urls would be the right name.

My configuration seems fine, the client uses photo-urls and it works as long as no Exception is thrown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM