DTO:
public class User {
@NotNull
private String name;
@NotNull
private String password;
//..
}
Controller:
For customized the error message in JSON format then do the below steps.
- Create one @Component called CommonErrorHandler
@Component
public class CommonErrorHandler {
public Map getFieldErrorResponse(BindingResult result){
Map fielderror = new HashMap<>();
Listerrors= result.getFieldErrors();
for (FieldError error : errors) {
fielderror.put(error.getField(), error.getDefaultMessage());
}return fielderror;
}
public ResponseEntity
-- Add InvalidException class
public class InvalidDataException extends RuntimeException {
/**
* @author Ashok Parmar
*/
private static final long serialVersionUID = -4164793146536667139L;
private BindingResult result;
public InvalidDataException(BindingResult result) {
super();
this.setResult(result);
}
public BindingResult getResult() {
return result;
}
public void setResult(BindingResult result) {
this.result = result;
}
}
- Introduce @ControllerAdvice class
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(InvalidDataException.class)
public ResponseEntity> invalidDataException(InvalidDataException ex, WebRequest request) {
List errors = ex.getResult().getFieldErrors();
for (FieldError error : errors) {
logger.error("Filed Name ::: " + error.getField() + "Error Message :::" + error.getDefaultMessage());
}
return commonErrorHandler.fieldErrorResponse("Error", commonErrorHandler.getFieldErrorResponse(ex.getResult()));
}
}
-- Use in controller with @Valid and throw exception
public AnyBeans update(**@Valid** @RequestBody AnyBeans anyBeans ,
BindingResult result) {
AnyBeans resultStr = null;
if (result.hasErrors()) {
**throw new InvalidDataException(result);**
} else {
resultStr = anyBeansService.(anyBeans );
return resultStr;
}
}
-- Output will be in JSON format
{
"timeStamp": 1590500231932,
"data": null,
"message": "Error",
"isSuccess": false,
"status": "BAD_REQUEST",
"filedError": {
"name": "Name is mandatory"
}
}
Hope this will be work. :-D