Polyphase29
Polyphase29

Reputation: 503

Getting FieldErrors from an ObjectError from a BindingResult

I'm trying to log errors returned to a controller from a validator class, but I'm only getting the ObjectError returned, which means I cannot log more specific information in my logger.

Ex:

    public void logErrors(BindingResult bindingResult){
        for (Object object : bindingResult.getAllErrors()) {
            if (object instanceof ObjectError) {
                ObjectError objectError = (ObjectError) object;
                logger.error("Bad request for " + ((FieldError) objectError).getField() + " of " + objectError.getObjectName() + " in myClass");
            }
            if (object instanceof FieldError) {
                FieldError fieldError = (FieldError) object;
                logger.error("Bad request for " + fieldError.getCode() + " of " + fieldError.getObjectName() + " in myClass");
            }
        }
}

This works as intended when receiving a fieldError, but trying to handle an ObjectError hasn't worked. As you can see above (and as was suggested in other threads), casting the ObjectError to a FieldError is suggested, but it won't work currently, stating that I cannot case an ObjectError to FieldError. Is there another way to accomplish what I'm looking for? Thanks!

edit: let me clarify by showing my validator class method, I'm testing by entering an ID that should throw a min error.

    @Override
    public void validate(Object target, Errors errors) {
        MyClass myClass = (MyClass) target;

        if(myCLass.getId() < 1000 || myClass.getId() > 100000) {
            errors.reject("myClass", "Id[must be between 1000 and 100000");
        }
    }

Simplified version of MyClass (its a POJO):

public class MyClass {

    private Long Id;

    public Long getId() {
        return Id;
    }

    public void setId(Long Id) {
        this.Id = Id;
    }
}

Upvotes: 2

Views: 3099

Answers (1)

armandino
armandino

Reputation: 18518

FieldError is a subclass of ObjectError, therefore you cannot cast ObjectError to FieldError.

With your current for loop you will get duplicate logs for FieldError since both if statements will evaluate to true. You could rewrite your for loop as follows:

public void logErrors(BindingResult bindingResult){
    for (ObjectError objectError : bindingResult.getAllErrors()) {
        if (objectError instanceof FieldError) {
            FieldError fieldError = (FieldError) objectError;
            logger.error(...); // log field error
        }
        else {
            logger.error(...); // log object error
        }
    }
}

If you are only interested in FieldErrors, there is also getFieldErrors() method you could use instead of getAllErrors().

Edit: Use rejectValue() instead of reject() to generate a field error.

Upvotes: 2

Related Questions