1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.spf4j.test.log.junit4;
17
18 import org.spf4j.test.log.ExceptionHandoverRegistry;
19 import java.util.ArrayList;
20 import java.util.List;
21 import java.util.concurrent.CopyOnWriteArrayList;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24 import org.spf4j.test.log.UncaughtExceptionDetail;
25 import org.spf4j.test.log.UncaughtExceptionConsumer;
26
27
28
29
30 class ExceptionAsserterUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler, ExceptionHandoverRegistry {
31
32 private static class Lazy {
33 private static final Logger LOG = LoggerFactory.getLogger(Lazy.class);
34 }
35
36 private final Thread.UncaughtExceptionHandler wrapped;
37
38 private final List<UncaughtExceptionConsumer> handovers;
39
40 private final List<UncaughtExceptionDetail> uncaughtExceptions;
41
42 ExceptionAsserterUncaughtExceptionHandler(final Thread.UncaughtExceptionHandler wrapped) {
43 this.wrapped = wrapped;
44 this.uncaughtExceptions = new CopyOnWriteArrayList<>();
45 this.handovers = new CopyOnWriteArrayList<>();
46 }
47
48 @Override
49 public void add(final UncaughtExceptionConsumer handover) {
50 handovers.add(handover);
51 }
52
53 @Override
54 public void remove(final UncaughtExceptionConsumer handover) {
55 handovers.remove(handover);
56 }
57
58 @Override
59 public void uncaughtException(final Thread t, final Throwable e) {
60 if (wrapped != null) {
61 wrapped.uncaughtException(t, e);
62 } else {
63 Lazy.LOG.debug("Uncaught Exception in thread {}", t, e);
64 }
65 UncaughtExceptionDetail exDetail = new UncaughtExceptionDetail(t, e);
66 boolean accepted = false;
67 for (UncaughtExceptionConsumer handover : handovers) {
68 if (handover.offer(exDetail)) {
69 accepted = true;
70 }
71 }
72 if (!accepted) {
73 uncaughtExceptions.add(exDetail);
74 }
75 }
76
77 public List<UncaughtExceptionDetail> getUncaughtExceptions() {
78 return new ArrayList<>(uncaughtExceptions);
79 }
80
81 @Override
82 public String toString() {
83 return "UncaughtExceptionAsserter{" + "wrapped=" + wrapped + ", handovers="
84 + handovers + ", uncaughtExceptions=" + uncaughtExceptions + '}';
85 }
86
87
88
89 }