-1

I have this code

import javax.validation.ValidationException;

    /**
     * Exception handler for validation exceptions.
     * Handles exceptions related to validation data, such as validation errors.
     * Returns a ResponseEntity with the appropriate error code, message, and HTTP
     * status code 400 (Bad Request).
     */
    @ExceptionHandler(ValidationException.class)
    public ResponseEntity<ApiError> handleValidationException(ValidationException exception) {
            return buildResponseEntity(ErrorCodes.INVALID_NUMBER,
                            "The number must be a whole number between 0 & " + Long.MAX_VALUE, null,
                            HttpStatus.BAD_REQUEST);
    }

I would like the message to include the name of the field that is not a number the end result shoud be something like this "The number must be a whole number between 0 & " + Long.MAX_VALUE + " for the field " + NAME_OF_FIELD How can i do this in java.

4
  • 1
    Are you referring to jakarta.validation.ValidationException? Then you should state this in the question and also add an appropriate tag to the question. Commented Jun 18 at 12:55
  • @SpaceTrucker no i am using import javax.validation.ValidationException; Thank you for pointing out that I didn’t mention this in my question.
    – J.C
    Commented Jun 18 at 13:07
  • Does this answer your question? Can I get all validation errors in spring boot web application? Commented Jun 18 at 13:08
  • @ArunSudhakaran I am using ValidationException and not MethodArgumentNotValidException . But thank you for your help.
    – J.C
    Commented Jun 18 at 13:09

1 Answer 1

1

Method of ExceptionHandler can accept more then one parameter. In particular it can accept HttpServletRequest. The last has "query string" where all fields and values present. With some efforts we can use this info to improve error message.

Here is a simplest reproducible example

@RestController
@Validated
public class MyController {

    @GetMapping
    public String get(@Min(0) Integer value) {
        return "Hello, world!";
    }

    @ExceptionHandler
    public ResponseEntity<String> handle(ValidationException exception, HttpServletRequest request) {
        String field = request.getQueryString().split("=")[0];
        String errorMessage = exception.getMessage() + " for field " + field;
        return new ResponseEntity<>(errorMessage, null, HttpStatus.BAD_REQUEST);
    }
}

Test it

curl http://localhost:8080?value=-1

Test result

get.value: must be greater than or equal to 0 for field value

Not the answer you're looking for? Browse other questions tagged or ask your own question.