Handle duplicate account key issue gracefully
Change transaction propagation to SUPPORTS for that as otherwise an UnexpectedRollbackException gets thrown
This commit is contained in:
@@ -28,7 +28,8 @@ public enum ResponseReason {
|
||||
MISSING_TRANSACTION_ID(HttpStatus.INTERNAL_SERVER_ERROR),
|
||||
INVALID_TRANSACTION_ID(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;
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
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#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) {
|
||||
if (!AccountType.isValidType(type)) {
|
||||
return ResponseReason.INVALID_ACCOUNT_TYPE;
|
||||
@@ -79,6 +80,11 @@ public class AccountService {
|
||||
try {
|
||||
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) {
|
||||
LOGGER.error(String.format("Could not save account %s|%s", key, type), e);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user