View Javadoc

1   /**
2    * Copyright © 2018 spring-data-dynamodb (https://github.com/derjust/spring-data-dynamodb)
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.socialsignin.spring.data.dynamodb.utils;
17  
18  import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
19  import org.springframework.dao.DataAccessException;
20  
21  import java.lang.reflect.Constructor;
22  import java.lang.reflect.InvocationTargetException;
23  import java.util.LinkedList;
24  import java.util.List;
25  import java.util.Queue;
26  import java.util.stream.Collectors;
27  
28  public interface ExceptionHandler {
29  
30  	default <T extends DataAccessException> T repackageToException(List<DynamoDBMapper.FailedBatch> failedBatches,
31  			Class<T> targetType) {
32  		// Error handling:
33  		Queue<Exception> allExceptions = failedBatches.stream().map(it -> it.getException())
34  				.collect(Collectors.toCollection(LinkedList::new));
35  
36  		// The first exception is hopefully the cause
37  		Exception cause = allExceptions.poll();
38  		try {
39  			Constructor<T> ctor = targetType.getConstructor(String.class, Throwable.class);
40  			T e = ctor.newInstance("Processing of entities failed!", cause);
41  			// and all other exceptions are 'just' follow-up exceptions
42  			allExceptions.stream().forEach(e::addSuppressed);
43  			return e;
44  		} catch (NoSuchMethodException | InstantiationException | IllegalAccessException
45  				| InvocationTargetException e) {
46  			assert false; // we should never end up here
47  			throw new RuntimeException("Could not repackage '" + failedBatches + "' to " + targetType, e);
48  		}
49  	}
50  }