In the outermost layer, catch the exception as follows:
try {
newEntity = ourService.createUpdate(entity);
} catch (JpaSystemException jpae) {
if (jpae.getCause().getCause() instanceof ConstraintViolationException) {
if (((ConstraintViolationException)jpae.getCause().getCause()).getConstraintName().equals("SCHEMA.UK_CODE_01")){
throw new DuplicatedCodeException("Message",jpae);
} else if (((ConstraintViolationException)jpae.getCause().getCause()).getConstraintName().equals("SCHEMA.UK_NAME_01")){
throw new DuplicatedNameException("Message",jpae);
}
}
}
Create a custom exception for each unique key like this:
public class DuplicatedNameException extends Exception {
public DuplicatedNameException(String message){
super(message);
}
public DuplicatedNameException(String message, Throwable anException){
super(message, anException);
}
}
Define an exception handler that extends from the ResponseEntityExceptionHandler class and treats the received exception as follows:
@ExceptionHandler({ DuplicatedNameException.class })
public ResponseEntity<Object> handleDuplicatedNameException(Exception anException, WebRequest request) {
[...]
return new ResponseEntity<>(anException, new HttpHeaders(), YOUR_HTTP_STATUS_WITH_CUSTOM_CODE_HERE);
}
This HTTPStatus is the one that you should check in the web layer to show the error message