0

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.

5
  • This isn't a JPA issue - it is a container issue. What container are you using and how have you configured it to handle your UniqueFieldViolation? It needs to be setup so that it returns a 409 status code for that error, and looks like it is using the default 500 for all errors Commented Jan 13 at 14:11
  • I'm not sure what you mean by container. I'm still pretty new to this. Commented Jan 14 at 1:18
  • container: technology you are using to run your code and handle your Rest and other controllers. Commented Jan 14 at 16:02
  • IntelliJ for the coding and Postman for testing CRUD Commented Jan 14 at 16:07
  • IntelliJ is where you do the coding; it doesn't create REST api for your postman client to hit. Are you maybe using Spring boot? This stuff will show up in your exceptions stack trace. Regardless, you'll need to check your server configuration and set it up so that it treats your UniqueFieldViolation as a 409, or have your REST api controller catch the exception and return a 409 response yourself Commented Jan 15 at 14:24

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.