spring-data-relational icon indicating copy to clipboard operation
spring-data-relational copied to clipboard

Spring Data JDBC throws DbActionExecutionException, which is the correct exception handling?

Open cypher256 opened this issue 4 years ago • 1 comments

I think the way to use PersistenceExceptionTranslator is better, is there any problem with it? Related issue: #831 save() method is raising a DbActionExecutionException on unique key violation

// Catch DbActionExecutionException and resolve by instanceof.
try {
	--- Access Spring Data JDBC Repository ---
} catch (DbActionExecutionException e) {
	if (e.getCause() instanceof DuplicateKeyException) {
		//
	} else if (e.getCause() instanceof OptimisticLockingFailureException) {
		//
	} else {
		throw e;
	}
}
// Define an Exception Translator bean to convert DbActionExecutionException to DataAccessException.
@Bean
public PersistenceExceptionTranslator exceptionTranslator() {
	return new PersistenceExceptionTranslator() {
		@Override
		public DataAccessException translateExceptionIfPossible(RuntimeException e) {
			if (e instanceof DataAccessException) {
				return (DataAccessException) e;
			}
			if (e.getCause() instanceof DataAccessException) {
				return (DataAccessException) e.getCause();
			}
			return null;
		}
	};
}

try {
	--- Access Spring Data JDBC Repository ---
} catch (DuplicateKeyException e) {
	//
} catch (OptimisticLockingFailureException e) {
	//
}

cypher256 avatar Nov 16 '21 07:11 cypher256

I agree we should support the use of exception translators. Therefore the JdbcAggregateTemplate should invoke the exception translation handling.

schauder avatar Feb 15 '22 09:02 schauder