com.bluecatcode.common.base.ExceptionSupplier Maven / Gradle / Ivy
The newest version!
package com.bluecatcode.common.base;
import com.google.common.base.Supplier;
/**
* Optional supplier for exceptions
*
* The supplier is designed to be used for more DSL-like usage of the following pattern:
*
* {@code}
*
* Optional<Something> optionalSomething = ...;
* if (!optional.isPresent()) {
* throw new SomeException();
* }
* Something something = optionalSomething.get();
*
* {@code}
* As shown here:
*
* Something something = optionalSomething.or(throwA(Something.class, new SomeException()));
*
*
* @see com.google.common.base.Optional#or(Supplier)
*/
public class ExceptionSupplier implements Supplier {
private final E exception;
private ExceptionSupplier(E exception) {
this.exception = exception;
}
/**
* Factory method for usage during variable or field initialisation.
*
* @param exception exception to throw
* @param Supplied object type
* @param RuntimeException subtype
* @return the exception supplier
* @throws E the provided exception
*/
public static ExceptionSupplier throwA(E exception) {
return new ExceptionSupplier<>(exception);
}
/**
* Factory method for usage inside a method call
*
* @param type class type used only for type inference
* @param exception exception to throw
* @param Supplied object type
* @param RuntimeException subtype
* @return the exception supplier
* @throws E the provided exception
*/
public static ExceptionSupplier throwA(
@SuppressWarnings("UnusedParameters") Class type, E exception) {
return new ExceptionSupplier<>(exception);
}
/**
*{@inheritDoc}
*/
@Override
public T get() {
throw exception;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy