简体   繁体   English

Spring 引导:如何从 FieldError.getField() 获取序列化名称

[英]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?有没有办法在使用FieldError.getField()方法捕获MethodArgumentNotValidExceptionsExceptionHandler中获取序列化名称?

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

I have my POJO with the entry我有我的 POJO 和条目

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

and this code in the ExceptionHandler :以及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 .并且只要缺少此字段(违反@NotNull约束), getField()就会返回photoUrls而不是photo-urls But the for client photo-urls would be the right name.但客户photo-urls将是正确的名称。

My configuration seems fine, the client uses photo-urls and it works as long as no Exception is thrown.我的配置看起来不错,客户端使用photo-urls ,只要没有抛出异常,它就可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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