Search code examples
javaspringspring-bootspring-boot-starter

Spring Boot Validation - How to retrieve input message in MethodArgumentNotValidException handler


I am using spring-boot-starter-validation dependency to validate java beans for my application

My Controller code as below

@PostMapping("/testMessage")
    ResponseEntity<String> testMethod(@Valid @RequestBody InternalMsg internalMsg) {
        return ResponseEntity.ok("Valid Message");
    }

InternalMsg class

public class InternalMsg implements Serializable {
    @NotNull(message = "Msg Num is a required field")
    private String msgNumber;
    @NotEmpty(message = "Activity Name is a required field")
    private String activityName;
}

InternalMsg Sample Input JSON

{
    "MSGNUMBER": "12345",
    "ACTIVITYNAME": "",
}

My handler code as below

@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<InternalMsgResponse> handleValidationExceptions(
        MethodArgumentNotValidException ex) {
    InternalMsgResponse msg = new InternalMsgResponse();
    ex.getBindingResult().getAllErrors().forEach((error) -> {
        String errorMessage = error.getDefaultMessage(); // Error Message
        ack.setStatusNotes(errorMessage);
    });
    return ResponseEntity.ok().body(msg);
}

As per the sample input, the activity name is empty so I get a validation error message as "Activity Name is a required field".

For some other processing, I need to get the values of input Msg inside handler i.e I want to get msgNumber value(12345) which is a VALID value.

Is it possible? If so, please guide how to retrieve those values inside the handler.


Solution

  • You can call

    ex.getTarget()
    

    That will return the object. Then simply cast it to InternalMsg

    If you are using an older Spring Boot Version before 2.4.x then you must call

    ex.getBindingResult().getTarget()