001/* 002 * Copyright 2002-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.dao.support; 018 019import java.util.ArrayList; 020import java.util.List; 021 022import org.springframework.dao.DataAccessException; 023import org.springframework.lang.Nullable; 024import org.springframework.util.Assert; 025 026/** 027 * Implementation of {@link PersistenceExceptionTranslator} that supports chaining, 028 * allowing the addition of PersistenceExceptionTranslator instances in order. 029 * Returns {@code non-null} on the first (if any) match. 030 * 031 * @author Rod Johnson 032 * @author Juergen Hoeller 033 * @since 2.0 034 */ 035public class ChainedPersistenceExceptionTranslator implements PersistenceExceptionTranslator { 036 037 /** List of PersistenceExceptionTranslators. */ 038 private final List<PersistenceExceptionTranslator> delegates = new ArrayList<>(4); 039 040 041 /** 042 * Add a PersistenceExceptionTranslator to the chained delegate list. 043 */ 044 public final void addDelegate(PersistenceExceptionTranslator pet) { 045 Assert.notNull(pet, "PersistenceExceptionTranslator must not be null"); 046 this.delegates.add(pet); 047 } 048 049 /** 050 * Return all registered PersistenceExceptionTranslator delegates (as array). 051 */ 052 public final PersistenceExceptionTranslator[] getDelegates() { 053 return this.delegates.toArray(new PersistenceExceptionTranslator[0]); 054 } 055 056 057 @Override 058 @Nullable 059 public DataAccessException translateExceptionIfPossible(RuntimeException ex) { 060 for (PersistenceExceptionTranslator pet : this.delegates) { 061 DataAccessException translatedDex = pet.translateExceptionIfPossible(ex); 062 if (translatedDex != null) { 063 return translatedDex; 064 } 065 } 066 return null; 067 } 068 069}