I\'m trying to handle MethodArgumentNotValidException using @ControllerAdvice as code given below:
@ControllerAdvice
public class RestResponseEntityException
Handel Exception
@ControllerAdvice
@RestController
@Slf4j
public class ExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity
Customize Error Message
@Data
public class ErrorDetails {
private HttpStatus status;
private String message;
private List errors;
public ErrorDetails(HttpStatus status, String message, List errors) {
super();
this.status = status;
this.message = message;
this.errors = errors;
}
public ErrorDetails(HttpStatus status, String message, String error) {
super();
this.status = status;
this.message = message;
errors = Arrays.asList(error);
}
}
Sample Response
{
"status": "BAD_REQUEST",
"message": "Validation failed for argument [0] in public void com.ns.hospitalmanagement.resource.PatientResource.createPatient(com.ns.hospitalmanagement.entity.Patient) with 2 errors: [Field error in object 'patient' on field 'name': rejected value [null]; codes [NotNull.patient.name,NotNull.name,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [patient.name,name]; arguments []; default message [name]]; default message [Name Can not be Null]] [Field error in object 'patient' on field 'name': rejected value [null]; codes [NotEmpty.patient.name,NotEmpty.name,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [patient.name,name]; arguments []; default message [name]]; default message [Name Can not be Empty]] ",
"errors": [
"Name Can not be Null",
"Name Can not be Empty"
]
}