I have a custom advice to handle exceptions from controllers copied from REST API Error Handling and a method to handle DataIntegrityViolationException:
@ExceptionHandler(DataIntegrityViolationException.class)
protected ResponseEntity<Object> handleDataIntegrityViolation(DataIntegrityViolationException ex,
WebRequest request) {
if (ex.getCause() instanceof ConstraintViolationException) {
return buildResponseEntity(new ApiError(HttpStatus.CONFLICT, "Database error", ex));
}
return buildResponseEntity(new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex));
}
ApiError - Constructor
public ApiError(HttpStatus status, String message, Throwable ex) {
this();
this.status = status;
this.message = message;
this.debugMessage = ex.getLocalizedMessage();
}
When an error happens the response shows a message like this one:
"apierror": {
"status": "CONFLICT",
"message": "Database error",
"debugMessage": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
"constraintName": null
}
The problem is that the message doesn't show a real problem to the consumer, because the real problem is inside (ex.getCause().getCause().getMessage()
):
Cannot delete or update a parent row: a foreign key constraint fails
(`cup_orchestrator`.`cpo_production_cycle`, CONSTRAINT `fk_cpo_production_cycle_cpo_cycle_type1`
FOREIGN KEY (`cycle_type_id`) REFERENCES `cpo_cycle_type` (`cycle_type_id`))
I'd like to handle to put a message like: "Record still have reference from other table";
Is there any custom handler exception to handle sql exceptions in a more specific way?