Constraint violations to API errors
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 exampleDuplicateKeyException). - Duplicates mean 409 Conflict; invalid data means 400 or 422.
- Catch it in one place: a
@RestControllerAdviceor 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
@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.
Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.