summaryrefslogtreecommitdiff
path: root/dicore3/core/src/main/java/io/dico/dicore/exceptions/checkedfunctions/CheckedConsumer.java
blob: fa48ae88c1b20593cbe0d4919c00e12623758de0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package io.dico.dicore.exceptions.checkedfunctions;

import io.dico.dicore.exceptions.ExceptionHandler;

import java.util.function.Consumer;

/**
 * checked mimic of {@link Consumer}
 *
 * @param <TParam>
 * @param <TException>
 */
@FunctionalInterface
public interface CheckedConsumer<TParam, TException extends Throwable>
        extends CheckedFunctionalObject<Void, TException>, Consumer<TParam> {
    
    /**
     * The consuming action
     *
     * @param t the argument to consume
     * @throws TException if an error occurs
     */
    void checkedAccept(TParam t) throws TException;
    
    /**
     * Unchecked version of {@link #checkedAccept(Object)}
     * If a {@link TException} occurs, an unchecked one might be thrown by {@link #resultOnError(Throwable, Object...)}
     *
     * @param t the argument to consume
     * @see #checkedAccept(Object)
     * @see #resultOnError(Throwable, Object...)
     */
    @Override
    default void accept(TParam t) {
        try {
            checkedAccept(t);
        } catch (Throwable ex) {
            handleGenericException(ex, t);
        }
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    default CheckedConsumer<TParam, TException> handleExceptionsWith(ExceptionHandler handler) {
        return new CheckedConsumer<TParam, TException>() {
            @Override
            public void checkedAccept(TParam t) throws TException {
                CheckedConsumer.this.checkedAccept(t);
            }
            
            @Override
            @SuppressWarnings("unchecked")
            public Void handleGenericException(Throwable thrown, Object... args) {
                handler.handleGenericException(thrown, args);
                return null;
            }
            
            @Override
            public CheckedConsumer<TParam, TException> handleExceptionsWith(ExceptionHandler handler) {
                return CheckedConsumer.this.handleExceptionsWith(handler);
            }
        };
    }
    
}