Skip to content

Commit

Permalink
Don't wrap exceptions thrown by component adapters (#1443)
Browse files Browse the repository at this point in the history
  • Loading branch information
swankjesse committed Dec 4, 2021
1 parent cdcf0da commit 81bf3b1
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
Expand Up @@ -17,10 +17,13 @@

import static com.google.common.truth.Truth.assertThat;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.junit.Assert.fail;

import com.squareup.moshi.FromJson;
import com.squareup.moshi.Json;
import com.squareup.moshi.JsonQualifier;
import com.squareup.moshi.JsonReader;
import com.squareup.moshi.JsonWriter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.ToJson;
import com.squareup.moshi.Types;
Expand All @@ -31,6 +34,7 @@
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import okio.Buffer;
import org.junit.Test;

public final class RecordsTest {
Expand Down Expand Up @@ -207,4 +211,41 @@ public void jsonName() throws IOException {
}

public static record JsonName(@Json(name = "actualValue") int value) {}

/**
* We had a bug where we were incorrectly wrapping exceptions thrown when delegating to the
* JsonAdapters of component fields.
*/
@Test
public void memberEncodeDecodeThrowsExceptionException() throws IOException {
var throwingAdapter =
new Object() {
@ToJson
void booleanToJson(JsonWriter writer, boolean value) throws IOException {
throw new IOException("boom!");
}

@FromJson
boolean booleanFromJson(JsonReader reader) throws IOException {
throw new IOException("boom!");
}
};
var json = "{\"value\":true}";
Moshi throwingMoshi = this.moshi.newBuilder().add(throwingAdapter).build();
var adapter = throwingMoshi.adapter(BooleanRecord.class);
try {
adapter.fromJson(json);
fail();
} catch (IOException expected) {
assertThat(expected).hasMessageThat().isEqualTo("boom!");
}
try {
adapter.toJson(new Buffer(), new BooleanRecord(true));
fail();
} catch (IOException expected) {
assertThat(expected).hasMessageThat().isEqualTo("boom!");
}
}

public static record BooleanRecord(boolean value) {}
}
Expand Up @@ -172,8 +172,9 @@ public void toJson(JsonWriter writer, T value) throws IOException {

for (var binding : componentBindingsArray) {
writer.name(binding.jsonName);
Object componentValue;
try {
binding.adapter.toJson(writer, binding.accessor.invoke(value));
componentValue = binding.accessor.invoke(value);
} catch (Throwable e) {
if (e instanceof InvocationTargetException ite) {
Throwable cause = ite.getCause();
Expand All @@ -184,6 +185,7 @@ public void toJson(JsonWriter writer, T value) throws IOException {
throw new AssertionError(e);
}
}
binding.adapter.toJson(writer, componentValue);
}

writer.endObject();
Expand Down

0 comments on commit 81bf3b1

Please sign in to comment.