'Custom validation spring boot not able to print the custom messages
I have created a pojo class and i need to validate the payload using custom validation approach. i have created separate constraints class for each field when i try to retrieve the validation message in response with MethodArgumentNotValidException in @controlleradvice it's not working.
Restcontroller
@PostMapping("/Add")
public String Add(@Valid @RequestBody CreditApprovalResponseEntity ca) {
log.info("START method - Add With : {}", ca);
log.info("END method - Add");
return "ok";
}
CreditApprovalResponseEntity
@AllArgsConstructor
@Getter
@Setter
@NoArgsConstructor
@ToString
@Builder
public class CreditApprovalResponseEntity {
@Caid
private String caId;
@Liability
private String liabilityId;
}
Liability.java
@Documented
@Constraint(validatedBy = LiabilityValidator.class)
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Liability {
String message() default "{LiabilityId should not be null or empty}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Caid.java
@Documented
@Constraint(validatedBy = CaidValidator.class)
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Caid {
String message() default "{Caid should not be null or empty}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Controlleradvice.java
@ControllerAdvice
public class ExceptionAdvice {
private static final Logger logger = LoggerFactory.getLogger(ExceptionAdvice.class);
@ExceptionHandler(value = { MethodArgumentNotValidException.class })
public ResponseEntity<List> handleException(HttpServletRequest req, MethodArgumentNotValidException ex) {
logger.error("RequestURI: {} Exception:{} message:{} ", req.getRequestURI(), ex, ex.getMessage());
List list = ex.getBindingResult().getAllErrors().stream().map(fieldError -> fieldError.getDefaultMessage())
.collect(Collectors.toList());
return new ResponseEntity<>(list, HttpStatus.BAD_REQUEST);
}
@ExceptionHandler(value = { Exception.class })
public ResponseEntity<Object> handleException(HttpServletRequest req, Exception ex) {
logger.error("RequestURI: {} Exception:{} message:{} ", req.getRequestURI(), ex, ex.getMessage());
Response resp = new Response();
ErrorList exceptions = new ErrorList();
resp.setException(exceptions);
return new ResponseEntity<Object>(resp, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(value = { BadRequestException.class })
public ResponseEntity<Object> handleException(HttpServletRequest req, BadRequestException ex) {
logger.error("RequestURI: {} Exception:{} message:{} ", req.getRequestURI(), ex, ex.getMessage());
Response resp = new Response();
ErrorList exceptions = new ErrorList();
resp.setException(exceptions);
return new ResponseEntity<Object>(resp, HttpStatus.BAD_REQUEST);
}
}
Unable to retrieve the validation messages from the constraint class because it is not hitting the MethodArguementException.class in controller advice instead it's going for Exception.class
It has to hit the MethodArguementException.class and response should be something like this.
[
Caid should not be null or empty,
LiabilityId should not be null or empty
]
Console
2022-03-18 14:55:19.748 INFO 24788 --- [ restartedMain] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2022-03-18 14:55:19.749 INFO 24788 --- [ restartedMain] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2022-03-18 14:55:19.764 INFO 24788 --- [ restartedMain] c.c.c.d.s.Application : Started Application in 46.048 seconds (JVM running for 48.809)
2022-03-18 14:55:19.773 INFO 24788 --- [ restartedMain] c.c.c.d.s.u.AppStartupRunner : Your application started with option names : []
2022-03-18 14:55:19.911 WARN 24788 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.web.bind.MethodArgumentNotValidException: Validation failed for argument [0] in public java.lang.String com.citi.cpb.dependencies.starter.controller.RestController.Add(com.citi.cpb.dependencies.starter.entity.CreditApprovalResponseEntity): [Field error in object 'creditApprovalResponseEntity' on field 'liabilityId': rejected value []; codes [Liability.creditApprovalResponseEntity.liabilityId,Liability.liabilityId,Liability.java.lang.String,Liability]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [creditApprovalResponseEntity.liabilityId,liabilityId]; arguments []; default message [liabilityId]]; default message [{LiabilityId should not be null or empty}]] ]
enter code here
Basically idea is to print all the validation messages of payload in single response
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
