All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.softicar.platform.common.core.exception.ExceptionsCollector Maven / Gradle / Ivy

Go to download

The SoftiCAR Platform is a lightweight, Java-based library to create interactive business web applications.

There is a newer version: 50.0.0
Show newest version
package com.softicar.platform.common.core.exception;

import com.softicar.platform.common.core.throwable.Throwables;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * Collects {@link Exception} objects and aggregates them into a single
 * {@link Exception}.
 *
 * @author Oliver Richers
 */
public class ExceptionsCollector {

	private final Collection exceptions;
	private String preamble;

	public ExceptionsCollector() {

		this.exceptions = new ArrayList<>();
		this.preamble = "";
	}

	public ExceptionsCollector setPreamble(String preamble, Object...arguments) {

		this.preamble = String.format(preamble, arguments);
		return this;
	}

	/**
	 * Adds the given {@link Exception} to this {@link ExceptionsCollector}.
	 * 

* If the given {@link Exception} is an {@link InterruptedException} or * caused by one, the added {@link Exception} will be wrapped in a * {@link RuntimeException}, and thrown. * * @param exception * the {@link Exception} (never null) * @return this */ public ExceptionsCollector add(Throwable exception) { exceptions.add(Objects.requireNonNull(exception)); if (Throwables.isCausedBy(InterruptedException.class, exception)) { throw new RuntimeException( "%s encountered an %s.".formatted(ExceptionsCollector.class.getSimpleName(), InterruptedException.class.getSimpleName()), exception); } return this; } /** * Returns whether this {@link ExceptionsCollector} is empty. * * @return true if no exceptions were added; false otherwise */ public boolean isEmpty() { return exceptions.isEmpty(); } /** * Returns all added {@link Exception} objects. * * @return all added {@link Exception} objects (never null) */ public Collection getExceptions() { return exceptions; } /** * Returns a combined error message for all added {@link Exception} objects. * * @return the error message (never null) */ public String getMessage() { return preamble + new MultiExceptionMessageBuilder(exceptions).buildMessage(); } /** * Throws a single {@link MultiException} containing information about all * added {@link Exception} objects. *

* If no exception was added, this method does nothing. */ public void throwIfNotEmpty() { if (!isEmpty()) { throw new MultiException(getMessage(), exceptions); } } /** * Calls the {@link Consumer} with the return value of * {@link #getMessage()}. *

* If no exception was added, this method does nothing. */ public void applyIfNotEmpty(Consumer messageConsumer) { if (!isEmpty()) { messageConsumer.accept(getMessage()); } } }





© 2015 - 2024 Weber Informatics LLC | Privacy Policy