Skip to content

Commit 06d777a

Browse files
hive-botclaude
andcommitted
fix: raise DeepLException for incomplete Write API responses
rephraseText() and correctText() now check that the response contains one complete improvement per input text. Before, an empty improvements list made the single-text overloads throw an IndexOutOfBoundsException, a null entry was returned as null, and the list overloads returned a short list without error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 3a607dd commit 06d777a

6 files changed

Lines changed: 62 additions & 6 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
125125
- Added `correctText()` to the `DeepLClient` class, which corrects grammar, spelling
126126
and punctuation using the `/v2/write/correct` endpoint. It accepts a single
127127
text or a list of texts, an optional target language and an optional
128-
`CorrectTextOptions`, which supports `setExtraBodyParameters()`.
128+
`CorrectTextOptions`, which supports `setExtraBodyParameters()`. A response
129+
without one complete result per input text raises a `DeepLException`.
129130
- Added `TextRephraseOptions.setWritingStyle(WritingStyle)` and
130131
`setTone(WritingTone)` overloads; the string setters remain.
131132
- `TextRephraseOptions` now extends `BaseRequestOptions` and supports
@@ -163,6 +164,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
163164
They will be removed in the next major version.
164165

165166
### Fixed
167+
- `rephraseText()` raises a `DeepLException` when the response does not
168+
contain one complete result per input text. Before, the single-text
169+
overload threw an `IndexOutOfBoundsException` or returned `null`, and the
170+
list overload returned a short list.
166171
- A document status the library does not know yet no longer stops
167172
`translateDocumentWaitUntilDone()` and `translateDocument()` with
168173
"Unknown error": it counts as in progress and polling continues.

‎README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -316,7 +316,8 @@ WriteResult result = client.correctText("A rainbouw has seven colours.", "EN-US"
316316
System.out.println(result.getText());
317317
```
318318

319-
Both functions return one `WriteResult` per input text.
319+
Both functions return one `WriteResult` per input text. A response that does
320+
not contain one complete result per input text raises a `DeepLException`.
320321

321322
### Translating documents
322323

‎deepl-java/src/main/java/com/deepl/api/DeepLClient.java‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,14 @@ private List<WriteResult> sendWriteRequest(
159159
httpClientWrapper.sendRequestWithBackoff(
160160
String.format("/%s/write/%s", apiVersion, operation), params);
161161
checkResponse(response, false, false);
162-
return jsonParser.parseWriteResult(response.getBody());
162+
List<WriteResult> results = jsonParser.parseWriteResult(response.getBody());
163+
if (results.size() != textCount || results.contains(null)) {
164+
throw new DeepLException(
165+
String.format(
166+
"Failed to parse the response of the DeepL API: expected %d improvements, got %d",
167+
textCount, results.size()));
168+
}
169+
return results;
163170
}
164171

165172
/**

‎deepl-java/src/main/java/com/deepl/api/parsing/WriteResultDeserializer.java‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,21 @@
1515
class WriteResultDeserializer implements JsonDeserializer<WriteResult> {
1616
public WriteResult deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
1717
throws JsonParseException {
18+
if (!json.isJsonObject()) {
19+
throw new JsonParseException("Write API improvement is not an object");
20+
}
1821
JsonObject jsonObject = json.getAsJsonObject();
1922
return new WriteResult(
20-
jsonObject.get("text").getAsString(),
21-
jsonObject.get("detected_source_language").getAsString(),
22-
jsonObject.get("target_language").getAsString());
23+
getRequiredString(jsonObject, "text"),
24+
getRequiredString(jsonObject, "detected_source_language"),
25+
getRequiredString(jsonObject, "target_language"));
26+
}
27+
28+
private static String getRequiredString(JsonObject jsonObject, String parameterName) {
29+
String value = Parser.getAsStringOrNull(jsonObject, parameterName);
30+
if (value == null) {
31+
throw new JsonParseException("Write API improvement is missing " + parameterName);
32+
}
33+
return value;
2334
}
2435
}

‎deepl-java/src/offlineTest/java/com/deepl/api/CorrectTextTest.java‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,19 @@ void sendsExtraBodyParametersLastReplacingSameKeyFields() throws Exception {
5555
.setExtraBodyParameters(Collections.singletonMap("target_lang", "de")));
5656
}
5757

58+
@Test
59+
void throwsDeepLExceptionWhenImprovementsAreShort() {
60+
wm.stubFor(post("/v2/write/correct").willReturn(okJson(REPLY)));
61+
assertThrows(
62+
DeepLException.class, () -> client.correctText(Arrays.asList("a", "b"), "en-GB", null));
63+
}
64+
65+
@Test
66+
void throwsDeepLExceptionWhenImprovementsAreEmpty() {
67+
wm.stubFor(post("/v2/write/correct").willReturn(okJson("{\"improvements\":[]}")));
68+
assertThrows(DeepLException.class, () -> client.correctText("a", "en-GB", null));
69+
}
70+
5871
@Test
5972
void sendsEveryTextOfAList() throws Exception {
6073
wm.stubFor(

‎deepl-java/src/offlineTest/java/com/deepl/api/RephraseTextTest.java‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,25 @@ void sendsExtraBodyParametersLastReplacingSameKeyFields() throws Exception {
9696
new TextRephraseOptions().setTone(WritingTone.Confident).setExtraBodyParameters(extra));
9797
}
9898

99+
@Test
100+
void throwsDeepLExceptionWhenImprovementsAreShort() {
101+
wm.stubFor(post("/v2/write/rephrase").willReturn(okJson(REPLY)));
102+
assertThrows(
103+
DeepLException.class, () -> client.rephraseText(Arrays.asList("a", "b"), "en-GB", null));
104+
}
105+
106+
@Test
107+
void throwsDeepLExceptionWhenImprovementsAreEmpty() {
108+
wm.stubFor(post("/v2/write/rephrase").willReturn(okJson("{\"improvements\":[]}")));
109+
assertThrows(DeepLException.class, () -> client.rephraseText("a", "en-GB", null));
110+
}
111+
112+
@Test
113+
void throwsDeepLExceptionWhenAnImprovementIsNull() {
114+
wm.stubFor(post("/v2/write/rephrase").willReturn(okJson("{\"improvements\":[null]}")));
115+
assertThrows(DeepLException.class, () -> client.rephraseText("a", "en-GB", null));
116+
}
117+
99118
@Test
100119
void sendsEveryTextOfAList() throws Exception {
101120
wm.stubFor(

0 commit comments

Comments
 (0)