Skip to content

Commit 2f1a4c7

Browse files
committed
Improve CallbackResultHolder exception message to aid debugging
JAVA-3038
1 parent d91cdce commit 2f1a4c7

File tree

2 files changed

+19
-5
lines changed

2 files changed

+19
-5
lines changed

config/checkstyle-exclude.xml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,9 @@
4343
<suppress checks="AvoidStarImportCheck" files=".*primer.*"/>
4444
<suppress checks="VisibilityModifierCheck" files=".*primer.*"/>
4545

46+
<!-- Allow printStackTrace in this file -->
47+
<suppress checks="Regexp" files="CallbackResultHolder"/>
48+
4649
<!--Do not check documentation tests classes -->
4750
<suppress checks="Javadoc*" files=".*documentation.*"/>
4851
<suppress checks="Regexp" files=".*documentation.*"/>

driver-core/src/test/unit/com/mongodb/async/CallbackResultHolder.java

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616

1717
package com.mongodb.async;
1818

19+
import java.io.PrintWriter;
20+
import java.io.StringWriter;
21+
1922
/**
2023
* A SingleResultCallback implementation that saves the result of the callback.
2124
*
@@ -35,13 +38,21 @@ class CallbackResultHolder<T> implements SingleResultCallback<T> {
3538
*/
3639
public void onResult(final T result, final Throwable error) {
3740
if (isDone) {
38-
throw new IllegalStateException("The CallbackResult cannot be initialized multiple times.");
41+
throw new IllegalStateException("The CallbackResult cannot be initialized multiple times. The first time it was initialized "
42+
+ "with " + (this.error != null ? getErrorString(this.error) : this.result) + "\n The second time it was initialized "
43+
+ "with " + (error != null ? getErrorString(error) : result));
3944
}
4045
this.result = result;
4146
this.error = error;
4247
this.isDone = true;
4348
}
4449

50+
private String getErrorString(final Throwable error) {
51+
StringWriter writer = new StringWriter();
52+
error.printStackTrace(new PrintWriter(writer));
53+
return writer.toString();
54+
}
55+
4556
/**
4657
* Returns the result of the callback or null.
4758
*
@@ -81,9 +92,9 @@ public boolean isDone() {
8192
@Override
8293
public String toString() {
8394
return "CallbackResultHolder{"
84-
+ "result=" + result
85-
+ ", error=" + error
86-
+ ", isDone=" + isDone
87-
+ '}';
95+
+ "result=" + result
96+
+ ", error=" + error
97+
+ ", isDone=" + isDone
98+
+ '}';
8899
}
89100
}

0 commit comments

Comments
 (0)