'Straightforward way of simplifying javax validation notations message

I've read several answers and question on how to custom handle validation errors on API request. However, it all seem a bit overkill. I have a simple object that is excepect in my endpoint:

@NotNull(message = "A target group must be provided")
@NotBlank(message = "Target group cannot be blank")
private String targetGroup;

@NotNull(message = "A target entity must be provided")
@NotBlank(message = "Target entity cannot be blank")
private String targetEntity;

@NotNull(message = "A target entity identifier must be provided")
@NotBlank(message = "Target entity identifier cannot be blank")
private String targetEntityIdentifier;

@NotNull(message = "A content must be provided")
@NotBlank(message = "Content cannot be blank")
private String content;

And the error thrown when I send a null or blank value is:

{
    "timestamp": "2022-02-03T15:01:43.296+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "JSON parse error: Cannot construct instance of `com.foo.notification.adapter.in.web.request.NotificationItemRequest`, problem: targetGroup: Target group cannot be blank, targetGroup: A target group must be provided; nested exception is com.fasterxml.jackson.databind.exc.ValueInstantiationException: Cannot construct instance of `com.foo.notification.adapter.in.web.request.NotificationItemRequest`, problem: targetGroup: Target group cannot be blank, targetGroup: A target group must be provided\n at [Source: (PushbackInputStream); line: 5, column: 1]",
    "path": "/notification"
}

This message is a bit too much to deliver to an front-end. Simply what they need is 'Target group cannot be blank'. I want to transform the message above into the following:

{
    "timestamp": "2022-02-03T15:01:43.296+00:00",
    "status": 400,
    "error": "Bad Request",
    "message": "A target group must be provided",
    "path": "/notification"
}

How can I accomplish that?



Solution 1:[1]

Use your custom handler, when the validation throws a constraint violation exception (javax.validation.ConstraintViolationException) handle it using a custom exception handler, so; you can simplify the response based on the usage.

For example:


@ControllerAdvice
public class SampleApiExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler
    public ResponseEntity<???> handle(ConstraintViolationException ex) {
        LOGGER.error("Domain violation error", ex);
        return badRequest().body("YOUR_RESPONSE_BODY");
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ibrahim AlTamimi