001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.eclipse.aether;
020
021import java.util.List;
022
023import static java.util.Objects.requireNonNull;
024
025/**
026 * Runtime exception to be thrown when multiple actions were executed and one or more failed. To be used when no
027 * fallback on resolver side is needed or is possible.
028 *
029 * @since 1.9.0
030 */
031public final class MultiRuntimeException extends RuntimeException {
032    /** The wrapped throwables. */
033    private final List<? extends Throwable> throwables;
034
035    private MultiRuntimeException(String message, List<? extends Throwable> throwables) {
036        super(message);
037        this.throwables = throwables;
038        for (Throwable throwable : throwables) {
039            addSuppressed(throwable);
040        }
041    }
042
043    /**
044     * Returns the list of throwables that are wrapped in this exception.
045     *
046     * @return The list of throwables, never {@code null}.
047     */
048    public List<? extends Throwable> getThrowables() {
049        return throwables;
050    }
051
052    /**
053     * Helper method that receives a (non-null) message and (non-null) list of throwable, and following happens:
054     * <ul>
055     *     <li>if list is empty - nothing</li>
056     *     <li>if list not empty - {@link MultiRuntimeException} is thrown wrapping all elements</li>
057     * </ul>
058     *
059     * @param message The exception message to use if a {@link MultiRuntimeException} is thrown, must not be
060     *            {@code null}.
061     * @param throwables The throwables to wrap, must not be {@code null}.
062     */
063    public static void mayThrow(String message, List<? extends Throwable> throwables) {
064        requireNonNull(message);
065        requireNonNull(throwables);
066
067        if (!throwables.isEmpty()) {
068            throw new MultiRuntimeException(message, throwables);
069        }
070    }
071}