Handle duplicate account key issue gracefully

Change transaction propagation to SUPPORTS for that as otherwise an UnexpectedRollbackException gets thrown
This commit is contained in:
2019-05-12 11:13:22 +02:00
parent c830a8e0b2
commit 148a1a4421
2 changed files with 9 additions and 2 deletions

View File

@@ -28,7 +28,8 @@ public enum ResponseReason {
MISSING_TRANSACTION_ID(HttpStatus.INTERNAL_SERVER_ERROR), MISSING_TRANSACTION_ID(HttpStatus.INTERNAL_SERVER_ERROR),
INVALID_TRANSACTION_ID(HttpStatus.INTERNAL_SERVER_ERROR), INVALID_TRANSACTION_ID(HttpStatus.INTERNAL_SERVER_ERROR),
TRANSACTION_NOT_FOUND(HttpStatus.INTERNAL_SERVER_ERROR), TRANSACTION_NOT_FOUND(HttpStatus.INTERNAL_SERVER_ERROR),
ACCOUNT_NOT_FOUND(HttpStatus.INTERNAL_SERVER_ERROR); ACCOUNT_NOT_FOUND(HttpStatus.INTERNAL_SERVER_ERROR),
DUPLICATE_ACCOUNT_KEY(HttpStatus.INTERNAL_SERVER_ERROR);
private HttpStatus httpStatus; private HttpStatus httpStatus;

View File

@@ -9,6 +9,7 @@ import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
@@ -61,7 +62,7 @@ public class AccountService {
* {@link ResponseReason#UNKNOWN_ERROR} if an unexpected error occurs and * {@link ResponseReason#UNKNOWN_ERROR} if an unexpected error occurs and
* {@link ResponseReason#OK} if the operation completed successfully. Never returns <code>null</code>. * {@link ResponseReason#OK} if the operation completed successfully. Never returns <code>null</code>.
*/ */
@Transactional(propagation = Propagation.REQUIRED) @Transactional(propagation = Propagation.SUPPORTS)
public ResponseReason createAccount(String key, String type) { public ResponseReason createAccount(String key, String type) {
if (!AccountType.isValidType(type)) { if (!AccountType.isValidType(type)) {
return ResponseReason.INVALID_ACCOUNT_TYPE; return ResponseReason.INVALID_ACCOUNT_TYPE;
@@ -79,6 +80,11 @@ public class AccountService {
try { try {
this.accountRepository.save(account); this.accountRepository.save(account);
} }
catch (DataIntegrityViolationException dive) {
LOGGER.error(String.format("Duplicate key! %s|%s", key, type), dive);
return ResponseReason.DUPLICATE_ACCOUNT_KEY;
}
catch (Exception e) { catch (Exception e) {
LOGGER.error(String.format("Could not save account %s|%s", key, type), e); LOGGER.error(String.format("Could not save account %s|%s", key, type), e);