Debian Codegraph @

src/main/java/io/reactivex/rxjava3/exceptions/CompositeException.java

raw
1 /*
2 * Copyright (c) 2016-present, RxJava Contributors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
5 * compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License is
10 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
11 * the License for the specific language governing permissions and limitations under the License.
12 */
13
14 package io.reactivex.rxjava3.exceptions;
15
16 import java.io.*;
17 import java.util.*;
18
19 import io.reactivex.rxjava3.annotations.NonNull;
20
21 /**
22 * Represents an exception that is a composite of one or more other exceptions. A {@code CompositeException}
23 * does not modify the structure of any exception it wraps, but at print-time it iterates through the list of
24 * Throwables contained in the composite in order to print them all.
25 *
26 * Its invariant is to contain an immutable, ordered (by insertion order), unique list of non-composite
27 * exceptions. You can retrieve individual exceptions in this list with {@link #getExceptions()}.
28 *
29 * The {@link #printStackTrace()} implementation handles the StackTrace in a customized way instead of using
30 * {@code getCause()} so that it can avoid circular references.
31 *
32 * If you invoke {@link #getCause()}, it will lazily create the causal chain but will stop if it finds any
33 * Throwable in the chain that it has already seen.
34 */
35 public final class CompositeException extends RuntimeException {
36
37 private static final long serialVersionUID = 3026362227162912146L;
38
39 private final List<Throwable> exceptions;
40 private final String message;
41 private Throwable cause;
42
43 /**
44 * Constructs a CompositeException with the given array of Throwables as the
45 * list of suppressed exceptions.
46 * @param exceptions the Throwables to have as initially suppressed exceptions
47 *
48 * @throws IllegalArgumentException if <code>exceptions</code> is empty.
49 */
50 public CompositeException(@NonNull Throwable... exceptions) {
51 this(exceptions == null ?
52 Collections.singletonList(new NullPointerException("exceptions was null")) : Arrays.asList(exceptions));
53 }
54
55 /**
56 * Constructs a CompositeException with the given array of Throwables as the
57 * list of suppressed exceptions.
58 * @param errors the Throwables to have as initially suppressed exceptions
59 *
60 * @throws IllegalArgumentException if <code>errors</code> is empty.
61 */
62 public CompositeException(@NonNull Iterable<? extends Throwable> errors) {
63 Set<Throwable> deDupedExceptions = new LinkedHashSet<>();
64 if (errors != null) {
65 for (Throwable ex : errors) {
66 if (ex instanceof CompositeException) {
67 deDupedExceptions.addAll(((CompositeException) ex).getExceptions());
68 } else
69 if (ex != null) {
70 deDupedExceptions.add(ex);
71 } else {
72 deDupedExceptions.add(new NullPointerException("Throwable was null!"));
73 }
74 }
75 } else {
76 deDupedExceptions.add(new NullPointerException("errors was null"));
77 }
78 if (deDupedExceptions.isEmpty()) {
79 throw new IllegalArgumentException("errors is empty");
80 }
81 List<Throwable> localExceptions = new ArrayList<>(deDupedExceptions);
82 this.exceptions = Collections.unmodifiableList(localExceptions);
83 this.message = exceptions.size() + " exceptions occurred. ";
84 }
85
86 /**
87 * Retrieves the list of exceptions that make up the {@code CompositeException}.
88 *
89 * @return the exceptions that make up the {@code CompositeException}, as a {@link List} of {@link Throwable}s
90 */
91 @NonNull
92 public List<Throwable> getExceptions() {
93 return exceptions;
94 }
95
96 @Override
97 @NonNull
98 public String getMessage() {
99 return message;
100 }
101
102 @Override
103 @NonNull
104 public synchronized Throwable getCause() { // NOPMD
105 if (cause == null) {
106 String separator = System.getProperty("line.separator");
107 if (exceptions.size() > 1) {
108 Map<Throwable, Boolean> seenCauses = new IdentityHashMap<>();
109
110 StringBuilder aggregateMessage = new StringBuilder();
111 aggregateMessage.append("Multiple exceptions (").append(exceptions.size()).append(")").append(separator);
112
113 for (Throwable inner : exceptions) {
114 int depth = 0;
115 while (inner != null) {
116 for (int i = 0; i < depth; i++) {
117 aggregateMessage.append(" ");
118 }
119 aggregateMessage.append("|-- ");
120 aggregateMessage.append(inner.getClass().getCanonicalName()).append(": ");
121 String innerMessage = inner.getMessage();
122 if (innerMessage != null && innerMessage.contains(separator)) {
123 aggregateMessage.append(separator);
124 for (String line : innerMessage.split(separator)) {
125 for (int i = 0; i < depth + 2; i++) {
126 aggregateMessage.append(" ");
127 }
128 aggregateMessage.append(line).append(separator);
129 }
130 } else {
131 aggregateMessage.append(innerMessage);
132 aggregateMessage.append(separator);
133 }
134
135 for (int i = 0; i < depth + 2; i++) {
136 aggregateMessage.append(" ");
137 }
138 StackTraceElement[] st = inner.getStackTrace();
139 if (st.length > 0) {
140 aggregateMessage.append("at ").append(st[0]).append(separator);
141 }
142
143 if (!seenCauses.containsKey(inner)) {
144 seenCauses.put(inner, true);
145
146 inner = inner.getCause();
147 depth++;
148 } else {
149 inner = inner.getCause();
150 if (inner != null) {
151 for (int i = 0; i < depth + 2; i++) {
152 aggregateMessage.append(" ");
153 }
154 aggregateMessage.append("|-- ");
155 aggregateMessage.append("(cause not expanded again) ");
156 aggregateMessage.append(inner.getClass().getCanonicalName()).append(": ");
157 aggregateMessage.append(inner.getMessage());
158 aggregateMessage.append(separator);
159 }
160 break;
161 }
162 }
163 }
164
165 cause = new ExceptionOverview(aggregateMessage.toString().trim());
166 } else {
167 cause = exceptions.get(0);
168 }
169 }
170 return cause;
171 }
172
173 /**
174 * All of the following {@code printStackTrace} functionality is derived from JDK {@link Throwable}
175 * {@code printStackTrace}. In particular, the {@code PrintStreamOrWriter} abstraction is copied wholesale.
176 *
177 * Changes from the official JDK implementation:<ul>
178 * <li>no infinite loop detection</li>
179 * <li>smaller critical section holding {@link PrintStream} lock</li>
180 * <li>explicit knowledge about the exceptions {@link List} that this loops through</li>
181 * </ul>
182 */
183 @Override
184 public void printStackTrace() {
185 printStackTrace(System.err);
186 }
187
188 @Override
189 public void printStackTrace(PrintStream s) {
190 printStackTrace(new WrappedPrintStream(s));
191 }
192
193 @Override
194 public void printStackTrace(PrintWriter s) {
195 printStackTrace(new WrappedPrintWriter(s));
196 }
197
198 /**
199 * Special handling for printing out a {@code CompositeException}.
200 * Loops through all inner exceptions and prints them out.
201 *
202 * @param output
203 * stream to print to
204 */
205 private void printStackTrace(PrintStreamOrWriter output) {
206 output.append(this).append("\n");
207 for (StackTraceElement myStackElement : getStackTrace()) {
208 output.append("\tat ").append(myStackElement).append("\n");
209 }
210 int i = 1;
211 for (Throwable ex : exceptions) {
212 output.append(" ComposedException ").append(i).append(" :\n");
213 appendStackTrace(output, ex, "\t");
214 i++;
215 }
216 output.append("\n");
217 }
218
219 private void appendStackTrace(PrintStreamOrWriter output, Throwable ex, String prefix) {
220 output.append(prefix).append(ex).append('\n');
221 for (StackTraceElement stackElement : ex.getStackTrace()) {
222 output.append("\t\tat ").append(stackElement).append('\n');
223 }
224 if (ex.getCause() != null) {
225 output.append("\tCaused by: ");
226 appendStackTrace(output, ex.getCause(), "");
227 }
228 }
229
230 abstract static class PrintStreamOrWriter {
231 /**
232 * Prints the object's string representation via the underlying PrintStream or PrintWriter.
233 * @param o the object to print
234 * @return this
235 */
236 abstract PrintStreamOrWriter append(Object o);
237 }
238
239 /**
240 * Same abstraction and implementation as in JDK to allow PrintStream and PrintWriter to share implementation.
241 */
242 static final class WrappedPrintStream extends PrintStreamOrWriter {
243 private final PrintStream printStream;
244
245 WrappedPrintStream(PrintStream printStream) {
246 this.printStream = printStream;
247 }
248
249 @Override
250 WrappedPrintStream append(Object o) {
251 printStream.print(o);
252 return this;
253 }
254 }
255
256 /**
257 * Same abstraction and implementation as in JDK to allow PrintStream and PrintWriter to share implementation.
258 */
259 static final class WrappedPrintWriter extends PrintStreamOrWriter {
260 private final PrintWriter printWriter;
261
262 WrappedPrintWriter(PrintWriter printWriter) {
263 this.printWriter = printWriter;
264 }
265
266 @Override
267 WrappedPrintWriter append(Object o) {
268 printWriter.print(o);
269 return this;
270 }
271 }
272
273 /**
274 * Contains a formatted message with a simplified representation of the exception graph
275 * contained within the CompositeException.
276 */
277 static final class ExceptionOverview extends RuntimeException {
278
279 private static final long serialVersionUID = 3875212506787802066L;
280
281 ExceptionOverview(String message) {
282 super(message);
283 }
284
285 @Override
286 public synchronized Throwable fillInStackTrace() {
287 return this;
288 }
289 }
290
291 /**
292 * Returns the number of suppressed exceptions.
293 * @return the number of suppressed exceptions
294 */
295 public int size() {
296 return exceptions.size();
297 }
298 }