summaryrefslogtreecommitdiff
path: root/dicore3/core/src/main/java/io/dico/dicore/exceptions/checkedfunctions/CheckedRunnable.java
blob: 110c9884bd450da945536bb38157579ced21e19e (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
package io.dico.dicore.exceptions.checkedfunctions;

import io.dico.dicore.exceptions.ExceptionHandler;

/**
 * checked mimic of {@link Runnable}
 *
 * @param <TException>
 */
@FunctionalInterface
public interface CheckedRunnable<TException extends Throwable>
        extends CheckedFunctionalObject<Void, TException>, Runnable {
    
    /**
     * The runnable action
     *
     * @throws TException if an exception occurs
     */
    void checkedRun() throws TException;
    
    /**
     * Unchecked version of {@link #checkedRun()}
     * If a {@link TException} occurs, an unchecked one might be thrown by {@link #resultOnError(Throwable, Object...)}
     *
     * @see #checkedRun()
     * @see #resultOnError(Throwable, Object...)
     */
    @Override
    default void run() {
        try {
            checkedRun();
        } catch (Throwable ex) {
            handleGenericException(ex);
        }
    }
    
    /**
     * {@inheritDoc}
     */
    @Override
    default CheckedRunnable<TException> handleExceptionsWith(ExceptionHandler handler) {
        return new CheckedRunnable<TException>() {
            @Override
            public void checkedRun() throws TException {
                CheckedRunnable.this.checkedRun();
            }
            
            @Override
            @SuppressWarnings("unchecked")
            public Void handleGenericException(Throwable thrown, Object... args) {
                handler.handleGenericException(thrown, args);
                return null;
            }
            
            @Override
            public CheckedRunnable<TException> handleExceptionsWith(ExceptionHandler handler) {
                return CheckedRunnable.this.handleExceptionsWith(handler);
            }
        };
    }
    
}