Not getting proper response while bean validation failed in spring boot app
I am using spring boot 2.0.6, hibernate validator 6.0, validation-api 2.0, and apache cxf. I used @Valid annotation in controler method and then i set @NotNull, @Email with proper messages in bean properties. Then I created a CustomExceptionHandler to handle the MethodArgumentNotValidException. while testing it by postman i am not getting the proper response with my validation message.
UserController.class
@Path("/user")
@Component
public class UserController {
@POST
@Path("/register")
@Consumes(MediaType.APPLICATION_JSON_VALUE)
@Produces(MediaType.APPLICATION_JSON_VALUE)
public Response registerUser(@Valid User user) {
String status = "";
Boolean isEmailIdExist = UserAuthService.checkUserByMailId(user.getEmail());
Boolean isUserNameExist = UserAuthService.checkUserByUserName(user.getUserName());
if(!isEmailIdExist) {
if(!isUserNameExist) {
status = UserAuthService.registerUser(user);
}else {
status = "Username already taken. Try with different name";
}
}else {
status = "Email ID already exist";
}
return Response.ok(status).build();
}
}
User.class
@Entity
@Table(name = "USER")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "UID")
private int userId;
@NotBlank(message = "Please provide first name")
@Column(name = "FIRST_NAME", length = 50)
private String firstName;
@NotBlank(message = "Please provide email")
@Column(name = "EMAIL", length = 100, unique = true)
@Email(message = "Please provide a valid email")
private String email;}
getter/setter
}
CustomExceptionHandler.java
@ControllerAdvice
@Component
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<Object>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), "Validation Failed", ex.getBindingResult().toString());
return new ResponseEntity<Object>(errorDetails, HttpStatus.BAD_REQUEST);
}
}
Json Structure
{
"firstName":"",
"email":"prakashkumar@xyz.com",
}
java spring-boot cxf hibernate-validator
|
show 2 more comments
I am using spring boot 2.0.6, hibernate validator 6.0, validation-api 2.0, and apache cxf. I used @Valid annotation in controler method and then i set @NotNull, @Email with proper messages in bean properties. Then I created a CustomExceptionHandler to handle the MethodArgumentNotValidException. while testing it by postman i am not getting the proper response with my validation message.
UserController.class
@Path("/user")
@Component
public class UserController {
@POST
@Path("/register")
@Consumes(MediaType.APPLICATION_JSON_VALUE)
@Produces(MediaType.APPLICATION_JSON_VALUE)
public Response registerUser(@Valid User user) {
String status = "";
Boolean isEmailIdExist = UserAuthService.checkUserByMailId(user.getEmail());
Boolean isUserNameExist = UserAuthService.checkUserByUserName(user.getUserName());
if(!isEmailIdExist) {
if(!isUserNameExist) {
status = UserAuthService.registerUser(user);
}else {
status = "Username already taken. Try with different name";
}
}else {
status = "Email ID already exist";
}
return Response.ok(status).build();
}
}
User.class
@Entity
@Table(name = "USER")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "UID")
private int userId;
@NotBlank(message = "Please provide first name")
@Column(name = "FIRST_NAME", length = 50)
private String firstName;
@NotBlank(message = "Please provide email")
@Column(name = "EMAIL", length = 100, unique = true)
@Email(message = "Please provide a valid email")
private String email;}
getter/setter
}
CustomExceptionHandler.java
@ControllerAdvice
@Component
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<Object>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), "Validation Failed", ex.getBindingResult().toString());
return new ResponseEntity<Object>(errorDetails, HttpStatus.BAD_REQUEST);
}
}
Json Structure
{
"firstName":"",
"email":"prakashkumar@xyz.com",
}
java spring-boot cxf hibernate-validator
Can you provide what you are expecting and what you are getting?
– Pooja Aggarwal
Nov 22 '18 at 10:01
Hi @PoojaAggarwal. U can see my json structure. I am sending this json in postman and i should get a response with validation message "Please provide first name" but i am getting full exception stacktrace.
– Prakash kumar mallick
Nov 22 '18 at 10:11
Can you comment this method handleMethodArgumentNotValid and try.
– Pooja Aggarwal
Nov 22 '18 at 10:13
Again i got same exception. In eclipse console i am able to see the validation message.
– Prakash kumar mallick
Nov 22 '18 at 10:18
List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='Please provide first name', propertyPath=firstName, rootBeanClass=class com.airbus.argo.model.ArgoUser, messageTemplate='Please provide first name'} ]]
– Prakash kumar mallick
Nov 22 '18 at 10:19
|
show 2 more comments
I am using spring boot 2.0.6, hibernate validator 6.0, validation-api 2.0, and apache cxf. I used @Valid annotation in controler method and then i set @NotNull, @Email with proper messages in bean properties. Then I created a CustomExceptionHandler to handle the MethodArgumentNotValidException. while testing it by postman i am not getting the proper response with my validation message.
UserController.class
@Path("/user")
@Component
public class UserController {
@POST
@Path("/register")
@Consumes(MediaType.APPLICATION_JSON_VALUE)
@Produces(MediaType.APPLICATION_JSON_VALUE)
public Response registerUser(@Valid User user) {
String status = "";
Boolean isEmailIdExist = UserAuthService.checkUserByMailId(user.getEmail());
Boolean isUserNameExist = UserAuthService.checkUserByUserName(user.getUserName());
if(!isEmailIdExist) {
if(!isUserNameExist) {
status = UserAuthService.registerUser(user);
}else {
status = "Username already taken. Try with different name";
}
}else {
status = "Email ID already exist";
}
return Response.ok(status).build();
}
}
User.class
@Entity
@Table(name = "USER")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "UID")
private int userId;
@NotBlank(message = "Please provide first name")
@Column(name = "FIRST_NAME", length = 50)
private String firstName;
@NotBlank(message = "Please provide email")
@Column(name = "EMAIL", length = 100, unique = true)
@Email(message = "Please provide a valid email")
private String email;}
getter/setter
}
CustomExceptionHandler.java
@ControllerAdvice
@Component
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<Object>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), "Validation Failed", ex.getBindingResult().toString());
return new ResponseEntity<Object>(errorDetails, HttpStatus.BAD_REQUEST);
}
}
Json Structure
{
"firstName":"",
"email":"prakashkumar@xyz.com",
}
java spring-boot cxf hibernate-validator
I am using spring boot 2.0.6, hibernate validator 6.0, validation-api 2.0, and apache cxf. I used @Valid annotation in controler method and then i set @NotNull, @Email with proper messages in bean properties. Then I created a CustomExceptionHandler to handle the MethodArgumentNotValidException. while testing it by postman i am not getting the proper response with my validation message.
UserController.class
@Path("/user")
@Component
public class UserController {
@POST
@Path("/register")
@Consumes(MediaType.APPLICATION_JSON_VALUE)
@Produces(MediaType.APPLICATION_JSON_VALUE)
public Response registerUser(@Valid User user) {
String status = "";
Boolean isEmailIdExist = UserAuthService.checkUserByMailId(user.getEmail());
Boolean isUserNameExist = UserAuthService.checkUserByUserName(user.getUserName());
if(!isEmailIdExist) {
if(!isUserNameExist) {
status = UserAuthService.registerUser(user);
}else {
status = "Username already taken. Try with different name";
}
}else {
status = "Email ID already exist";
}
return Response.ok(status).build();
}
}
User.class
@Entity
@Table(name = "USER")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "UID")
private int userId;
@NotBlank(message = "Please provide first name")
@Column(name = "FIRST_NAME", length = 50)
private String firstName;
@NotBlank(message = "Please provide email")
@Column(name = "EMAIL", length = 100, unique = true)
@Email(message = "Please provide a valid email")
private String email;}
getter/setter
}
CustomExceptionHandler.java
@ControllerAdvice
@Component
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllExceptions(Exception ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<Object>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), "Validation Failed", ex.getBindingResult().toString());
return new ResponseEntity<Object>(errorDetails, HttpStatus.BAD_REQUEST);
}
}
Json Structure
{
"firstName":"",
"email":"prakashkumar@xyz.com",
}
java spring-boot cxf hibernate-validator
java spring-boot cxf hibernate-validator
edited Nov 22 '18 at 10:07
Prakash kumar mallick
asked Nov 22 '18 at 9:55
Prakash kumar mallickPrakash kumar mallick
46
46
Can you provide what you are expecting and what you are getting?
– Pooja Aggarwal
Nov 22 '18 at 10:01
Hi @PoojaAggarwal. U can see my json structure. I am sending this json in postman and i should get a response with validation message "Please provide first name" but i am getting full exception stacktrace.
– Prakash kumar mallick
Nov 22 '18 at 10:11
Can you comment this method handleMethodArgumentNotValid and try.
– Pooja Aggarwal
Nov 22 '18 at 10:13
Again i got same exception. In eclipse console i am able to see the validation message.
– Prakash kumar mallick
Nov 22 '18 at 10:18
List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='Please provide first name', propertyPath=firstName, rootBeanClass=class com.airbus.argo.model.ArgoUser, messageTemplate='Please provide first name'} ]]
– Prakash kumar mallick
Nov 22 '18 at 10:19
|
show 2 more comments
Can you provide what you are expecting and what you are getting?
– Pooja Aggarwal
Nov 22 '18 at 10:01
Hi @PoojaAggarwal. U can see my json structure. I am sending this json in postman and i should get a response with validation message "Please provide first name" but i am getting full exception stacktrace.
– Prakash kumar mallick
Nov 22 '18 at 10:11
Can you comment this method handleMethodArgumentNotValid and try.
– Pooja Aggarwal
Nov 22 '18 at 10:13
Again i got same exception. In eclipse console i am able to see the validation message.
– Prakash kumar mallick
Nov 22 '18 at 10:18
List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='Please provide first name', propertyPath=firstName, rootBeanClass=class com.airbus.argo.model.ArgoUser, messageTemplate='Please provide first name'} ]]
– Prakash kumar mallick
Nov 22 '18 at 10:19
Can you provide what you are expecting and what you are getting?
– Pooja Aggarwal
Nov 22 '18 at 10:01
Can you provide what you are expecting and what you are getting?
– Pooja Aggarwal
Nov 22 '18 at 10:01
Hi @PoojaAggarwal. U can see my json structure. I am sending this json in postman and i should get a response with validation message "Please provide first name" but i am getting full exception stacktrace.
– Prakash kumar mallick
Nov 22 '18 at 10:11
Hi @PoojaAggarwal. U can see my json structure. I am sending this json in postman and i should get a response with validation message "Please provide first name" but i am getting full exception stacktrace.
– Prakash kumar mallick
Nov 22 '18 at 10:11
Can you comment this method handleMethodArgumentNotValid and try.
– Pooja Aggarwal
Nov 22 '18 at 10:13
Can you comment this method handleMethodArgumentNotValid and try.
– Pooja Aggarwal
Nov 22 '18 at 10:13
Again i got same exception. In eclipse console i am able to see the validation message.
– Prakash kumar mallick
Nov 22 '18 at 10:18
Again i got same exception. In eclipse console i am able to see the validation message.
– Prakash kumar mallick
Nov 22 '18 at 10:18
List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='Please provide first name', propertyPath=firstName, rootBeanClass=class com.airbus.argo.model.ArgoUser, messageTemplate='Please provide first name'} ]]
– Prakash kumar mallick
Nov 22 '18 at 10:19
List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='Please provide first name', propertyPath=firstName, rootBeanClass=class com.airbus.argo.model.ArgoUser, messageTemplate='Please provide first name'} ]]
– Prakash kumar mallick
Nov 22 '18 at 10:19
|
show 2 more comments
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53428244%2fnot-getting-proper-response-while-bean-validation-failed-in-spring-boot-app%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53428244%2fnot-getting-proper-response-while-bean-validation-failed-in-spring-boot-app%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Can you provide what you are expecting and what you are getting?
– Pooja Aggarwal
Nov 22 '18 at 10:01
Hi @PoojaAggarwal. U can see my json structure. I am sending this json in postman and i should get a response with validation message "Please provide first name" but i am getting full exception stacktrace.
– Prakash kumar mallick
Nov 22 '18 at 10:11
Can you comment this method handleMethodArgumentNotValid and try.
– Pooja Aggarwal
Nov 22 '18 at 10:13
Again i got same exception. In eclipse console i am able to see the validation message.
– Prakash kumar mallick
Nov 22 '18 at 10:18
List of constraint violations:[ ConstraintViolationImpl{interpolatedMessage='Please provide first name', propertyPath=firstName, rootBeanClass=class com.airbus.argo.model.ArgoUser, messageTemplate='Please provide first name'} ]]
– Prakash kumar mallick
Nov 22 '18 at 10:19