Skip to content

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

Closed
@cypher256

Description

@cypher256

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) {
	//
}

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions