Skip to content
Ameen Abozaid
Planned lessonJNR-034-L03

Constraint violations to API errors

  • Lesson 3 of 5
  • Junior
On This Lesson 4 topics

This lesson is planned. The outline below lists the topics it will cover. The full lesson has not been published yet.

In this lesson

return meaningful HTTP errors for violations.

Planned topics

  • A violation reaches Spring as DataIntegrityViolationException (for example DuplicateKeyException).
  • Duplicates mean 409 Conflict; invalid data means 400 or 422.
  • Catch it in one place: a @RestControllerAdvice or the service where you can act.
  • Read the constraint name from the cause to choose the message (verify the exception path for your driver version).
  • Never leak SQL text to the client; use the problem-details format from earlier modules.
Draft outline details

Demonstration

java
@ExceptionHandler(DataIntegrityViolationException.class)
ProblemDetail conflict(DataIntegrityViolationException e) {
    return ProblemDetail.forStatusAndDetail(HttpStatus.CONFLICT, "SKU already exists");
}

Check your understanding

Which HTTP status for a duplicate SKU?

Show answer

409 Conflict.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.