Post

Foreign Key Validation Without Relying on DataIntegrityViolationException

Foreign Key Validation Without Relying on DataIntegrityViolationException

Situation

While implementing the Gift API at Kakao Tech Campus, I had to validate whether a product exists when creating a wishlist item. Initially, I just tried to insert and caught DataIntegrityViolationException.

1
2
3
4
5
6
7
public void addToWishlist(Long productId, Long memberId) {
    try {
        wishlistRepository.save(new WishlistItem(productId, memberId));
    } catch (DataIntegrityViolationException e) {
        throw new ProductNotFoundException(productId);
    }
}

Mentor Feedback

“DataIntegrityViolationException catches too many cases. It includes unique constraint violations, null violations, and more. Direct DB constraint exception handling isn’t very clean for business logic.”


Solution

Changed to explicitly check existence first.

1
2
3
4
5
6
public void addToWishlist(Long productId, Long memberId) {
    if (!productRepository.existsById(productId)) {
        throw new ProductNotFoundException(productId);
    }
    wishlistRepository.save(new WishlistItem(productId, memberId));
}

Trade-off

MethodProsCons
DataIntegrityViolationExceptionSingle queryCatches too many cases, unclear business logic
existsById checkClear business logic, specific error messagesAdditional query

Extra SELECT query is the cost. But in most cases, this cost is acceptable for clearer business logic.


Lessons Learned

  • Relying on DB exceptions for business logic isn’t clean
  • Explicit validation before operation makes code more readable
  • Define exception scope clearly - vague catch blocks are dangerous
  • Always consider what exception conditions exist and how to handle each

From Kakao Tech Campus 3rd cohort Gift API clone coding, summarizing mentor feedback.

This post is licensed under CC BY 4.0 by the author.