Zia
Zia

Reputation: 1011

javax.validation.constraints with custom Code and Message

I am using the javax.validation.constraints.NotEmpty library to validate POJO class for rest request. Within class i have used below annotaion.

@ApiModelProperty(value = "Name", required = true)
@NotEmpty(message = "Name is required")
private String name; 

Above code is working fine and returning the response as below when name is empty

 "code": "NotEmpty",
 "message": "Name is required" 

Is there any way through which i can display/provide the my own Custom code value instead of "code": "NotEmpty". Something like "code": "INVALID NAME".

Any approach suggestion on this must be appreciated.

Upvotes: 1

Views: 175

Answers (1)

Bill Mair
Bill Mair

Reputation: 1161

The best way is to implement your own exception handler and build the entire response as you need to it, as simple text, JSON, XML, etc..

@ControllerAdvice
class ExceptionAdvisor {
    @ExceptionHandler(ValidationException.class)
    ResponseEntity<MyErrorType> handleTypeMismatchException(ValidationException ex) {
        /*process all the constraint violations*/
        MyErrorType result = . . .;
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(result);
    }
}

There is also the Payload option:

public static class NameInvalid implements Payload {}
.
.
.
@NotEmpty(message = "Name is required", payload = NameInvalid.class)
private String name; 

Which should get you this:

"code": "NameInvalid",
"message": "Name is required" 

Upvotes: 1

Related Questions