GauravRatnawat
GauravRatnawat

Reputation: 859

Javax validation does not include field name

We have built an API in which in our model We have a field

@Min(1) @Max(16)
private Long demoField;

When we provide 17 to demoField it will throw us an error on the client-side

"must be less than or equal to 16"

But when we see the violation message it includes the field name and the message looks like

"demoField: must be less than or equal to 16"

So the question of why we are not getting field name in the client-side error message.

Am I missing something?

API built on spring boot

Upvotes: 1

Views: 1249

Answers (1)

Vlad L
Vlad L

Reputation: 1694

It's not passed by default. You could implement your own error handler to customize the message passed back, by using @ControllerAdvice for example.

One way is to just specify the message: @Min(value = 5, message="Age must be at least 5")

In which case in the @ControllerAdvice, you would just need to read getDefaultMessage()

If you don't want to manually add default messages, the approach would be to implement something along the lines of (with appropriate null checks etc):

package com.example.demo;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @Override
    protected ResponseEntity<Object> handleBindException(
            BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return new ResponseEntity<>(
                ex.getFieldError().getField() + ": " + ex.getFieldError().getDefaultMessage(),
                headers,
                status);
    }
}

Upvotes: 3

Related Questions