-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
ErrorHandler.java
104 lines (95 loc) · 3.02 KB
/
ErrorHandler.java
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/*
* Copyright (c) 2002-2018 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j Enterprise Edition. The included source
* code can be redistributed and/or modified under the terms of the
* GNU AFFERO GENERAL PUBLIC LICENSE Version 3
* (http://www.fsf.org/licensing/licenses/agpl-3.0.html) with the
* Commons Clause, as found in the associated LICENSE.txt file.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* Neo4j object code can be licensed independently from the source
* under separate terms from the AGPL. Inquiries can be directed to:
* licensing@neo4j.com
*
* More information is also available at:
* https://neo4j.com/licensing/
*/
package org.neo4j.causalclustering.helper;
import java.util.ArrayList;
import java.util.List;
public class ErrorHandler implements AutoCloseable
{
private final List<Throwable> throwables = new ArrayList<>();
private final String message;
/**
* Ensures each action is executed. Any throwables will be saved and thrown after all actions have been executed. The first caught throwable will be cause
* and any other will be added as suppressed.
*
* @param description The exception message if any are thrown.
* @param actions Throwing runnables to execute.
* @throws RuntimeException thrown if any action throws after all have been executed.
*/
public static void runAll( String description, ThrowingRunnable... actions ) throws RuntimeException
{
try ( ErrorHandler errorHandler = new ErrorHandler( description ) )
{
for ( ThrowingRunnable action : actions )
{
errorHandler.execute( action );
}
}
}
public ErrorHandler( String message )
{
this.message = message;
}
public void execute( ThrowingRunnable throwingRunnable )
{
try
{
throwingRunnable.run();
}
catch ( Throwable e )
{
throwables.add( e );
}
}
public void add( Throwable throwable )
{
throwables.add( throwable );
}
@Override
public void close() throws RuntimeException
{
throwIfException();
}
private void throwIfException()
{
if ( !throwables.isEmpty() )
{
RuntimeException runtimeException = null;
for ( Throwable throwable : throwables )
{
if ( runtimeException == null )
{
runtimeException = new RuntimeException( message, throwable );
}
else
{
runtimeException.addSuppressed( throwable );
}
}
throw runtimeException;
}
}
public interface ThrowingRunnable
{
void run() throws Throwable;
}
}