I'm working on a simple DB and I need to have an error 409 show up in Postman if when updating the patient record the email has already been used by another patient in the DB. I'm getting the 409 just fine when trying to add (POST) a new patient with a duplicate email, but on my PUT request I'm only getting error 500.
Here are my POST and PUT requests from PatientController:
/**
* Writes a new Patient to the database.
* @param patient - the Patient to write
* @return the created Patient
*/
public Patient addPatient(Patient patient) {
boolean emailExists;
try {
// check if email already exists
emailExists = patientRepository.existsByEmail(patient.getEmail());
} catch (Exception e) {
throw new ServiceUnavailable(e);
}
if (emailExists) {
throw new EmailAlreadyUsed("Email already used by another patient");
}
try {
return patientRepository.save(patient);
} catch (Exception e){
throw new ServiceUnavailable(e);
}
}
/**
* Update an existing Patient in the Database.
* @param id - the id of the Patient to update
* @param patient - the Patient information to update
* @return - the updated Patient, an error if email already exists in the Database, or a 404 if the Patient is not found
*/
public Patient updatePatientById(Long id, Patient patient) {
Patient existingPatient;
boolean emailIsSame;
boolean newEmailIsUnique;
String currentEmail;
//get the new eamil from the patient passed int
String newEmail = patient.getEmail();
//check if id in path matches id in request body
if (!patient.getId().equals(id)){
throw new BadDataResponse(StringConstants.BAD_REQUEST_ID);
}
try {
//get the existing patient from the database
existingPatient = patientRepository.findById(id).orElse(null);
if (existingPatient != null) {
//get the current email from the database
currentEmail = existingPatient.getEmail();
//see if new email already exists
newEmailIsUnique = !patientRepository.existsByEmail(newEmail);
// set local for email is same
emailIsSame = currentEmail.equals(newEmail);
// only continue if email has not changed, or new email is unique
if (emailIsSame || newEmailIsUnique) {
return patientRepository.save(patient);
}
}
} catch (Exception e) {
throw new ServiceUnavailable(e);
}
//if patient was not found...
if (existingPatient == null) {
throw new ResourceNotFound(StringConstants.BAD_REQUEST_PATIENT);
}
//customer was found so it must be because of an email conflict
else {
throw new UniqueFieldViolation(StringConstants.EMAIL_CONFLICT);
}
}
Here is the console log that shows it's triggering correctly in the DB when it happens.
edu.midlands.exceptions.UniqueFieldViolation: The email address is already associated with another patient
at edu.midlands.services.PatientServiceImpl.updatePatientById(PatientServiceImpl.java:140) ~[classes/:?]
at edu.midlands.controllers.PatientController.updatePatientById(PatientController.java:71) ~[classes/:?]
Maybe I have an Exception written wrong? Thank you for all the help.