`RestException.fromJson` throws `ApiException` on non-JSON error responses instead of returning `null`

Aperta Adatta ai principianti
#988 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
88/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
java
Ambito
api

Direzione di ricerca

Leggi src/main/java/com/twilio/exception/RestException.java nella parte relativa a fromJson, poi esamina src/test/java/com/twilio/exception/RestExceptionTest.java e i controlli null già presenti nei chiamanti. Esegui i test RestException con JSON malformato e casi di risposta non JSON; l’obiettivo è che entrambi restituiscano null, che il JSON valido continui a essere deserializzato e che i chiamanti possano usare il percorso di errore esistente per i contenuti assenti.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Previously reported (all closed, but the behaviour is still present on latest HEAD): https://github.com/twilio/twilio-java/issues/604 · https://github.com/twilio/twilio-java/issues/608 · https://github.com/twilio/twilio-java/issues/570

Describe the bug

Location (twilio/twilio-java @ default branch 0155569):

  • src/main/java/com/twilio/exception/RestException.java:63-64
    public static RestException fromJson(final InputStream json, final ObjectMapper objectMapper) {
        // Convert all checked exception to Runtime
        try {
            return objectMapper.readValue(json, RestException.class);
        } catch (final JsonMappingException | JsonParseException e) {
            throw new ApiException(e.getMessage(), e);
        } catch (final IOException e) {
            throw new ApiConnectionException(e.getMessage(), e);
        }
    }

When a Twilio API endpoint returns a non-JSON response body (e.g. an HTML 502 page), RestException.fromJson() throws an ApiException wrapping the JsonParseException instead of returning null.

This is inconsistent with how the rest of the codebase expects fromJson to behave: every caller checks if (restException == null) and, on that path, throws a clean "Server Error, no content" ApiException carrying the HTTP status code. Because fromJson throws before it can return, the callers' null-check becomes dead code and the user receives an opaque parse error rather than a meaningful HTTP error.

Actual behavior

RestException.fromJson() catches JsonParseException and immediately re-throws it as ApiException, preventing callers from handling the error gracefully via the existing null-check path.

Expected behavior

RestException.fromJson() returns null when the input stream does not contain valid JSON, so the caller can handle it through the existing if (restException == null) path.

Reproduction

Test applied on HEAD (src/test/java/com/twilio/exception/RestExceptionTest.java, relevant cases):

@Test
public void fromJsonShouldReturnNullForMalformedJson() {
    final String malformedJson =
            "{message\":test\", \"code:81022,\"more_info\": \"https://www.twilio.com/docs/errors/81022\"}";

    final RestException exception = RestException.fromJson(
            new ByteArrayInputStream(malformedJson.getBytes()), OBJECT_MAPPER);

    assertNull(exception);
}

@Test
public void fromJsonShouldReturnNullForNonJsonContent() {
    final String htmlContent = "<html><body>502 Bad Gateway</body></html>";

    final RestException exception = RestException.fromJson(
            new ByteArrayInputStream(htmlContent.getBytes()), OBJECT_MAPPER);

    assertNull(exception);
}

Failing output:

[ERROR] Tests run: 3, Failures: 0, Errors: 2, Skipped: 0 <<< FAILURE! -- in com.twilio.exception.RestExceptionTest
[ERROR] com.twilio.exception.RestExceptionTest.fromJsonShouldReturnNullForNonJsonContent -- Time elapsed: 0.006 s <<< ERROR!
Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
Caused by: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value ...

[ERROR] com.twilio.exception.RestExceptionTest.fromJsonShouldReturnNullForMalformedJson -- Time elapsed: 0.004 s <<< ERROR!
Unexpected character ('m' (code 109)): was expecting double-quote to start field name
Caused by: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('m' (code 109)): was expecting double-quote to start field name

[ERROR] Errors:
[ERROR]   RestExceptionTest.fromJsonShouldReturnNullForMalformedJson:38 » Api Unexpected character ('m' (code 109)): was expecting double-quote to start field name
[ERROR]   RestExceptionTest.fromJsonShouldReturnNullForNonJsonContent:48 » Api Unexpected character ('<' (code 60)): expected a valid value ...

fromJsonShouldDeserializeValidJson passes. The control run of the same suite without the test patch exits 0.

Environment:

  • Commit: 0155569 (2026-10-14), default branch
  • Toolchain: openjdk version "21.0.2" 2024-01-16 | Apache Maven 3.9.16

Already fixed in twilio/twilio-node

The analogous bug was fixed in the sibling project: PR https://github.com/twilio/twilio-node/pull/855 ("fix: update SMS messaging parse error"), merged 2023-01-03T20:56:23Z (merge commit 1508e52e712). It wraps the JSON parse in a try/catch and returns null on malformed/non-JSON bodies instead of letting the parse error propagate, so the exception is still constructed meaningfully.

How twilio-node fixed it:

--- a/lib/base/RestException.ts
+++ b/lib/base/RestException.ts
@@ -9,15 +16,28 @@ export default class RestException extends Error {
 
   constructor(response) {
     super("[HTTP " + response.statusCode + "] Failed to execute request");
+    const isResponseBodyString = typeof response.body == "string";
+    const body = isResponseBodyString
+      ? parseResponseBody(response.body)
+      : response.body;
 
-    const body =
-      typeof response.body === "string"
-        ? JSON.parse(response.body)
-        : response.body;
     this.status = response.statusCode;
-    this.message = body.message;
-    this.code = body.code;
-    this.moreInfo = body.more_info; /* jshint ignore:line */
-    this.details = body.details;
+    if (body !== null) {
+      this.message = body.message;
+      this.code = body.code;
+      this.moreInfo = body.more_info; /* jshint ignore:line */
+      this.details = body.details;
+    }
   }
 }
+
+function parseResponseBody(response_body: string): RestExceptionError | null {
+  let body = null;
+  try {
+    body = JSON.parse(response_body);
+  } catch (catchError) {
+    body = null;
+  }
+
+  return body;
+}

Suggested fix

Return null from RestException.fromJson() when the body is not valid JSON, so the existing caller null-check takes the "Server Error, no content" path, as twilio-node does:

diff --git a/src/main/java/com/twilio/exception/RestException.java b/src/main/java/com/twilio/exception/RestException.java
--- a/src/main/java/com/twilio/exception/RestException.java
+++ b/src/main/java/com/twilio/exception/RestException.java
@@ -61,7 +61,7 @@
         try {
             return objectMapper.readValue(json, RestException.class);
         } catch (final JsonMappingException | JsonParseException e) {
-            throw new ApiException(e.getMessage(), e);
+            return null;
         } catch (final IOException e) {
             throw new ApiConnectionException(e.getMessage(), e);
         }

Verified on 0155569 (OpenJDK 21.0.2, Maven 3.9.6): the test above fails without this patch and passes with it; no other test results change.

twilio-java version

latest HEAD 0155569

Java version

OpenJDK 21.0.2

Lingua principale
Java
Stelle
528
Fork
462
Merge medio
2g 11h
PR unite (30g)
4

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di twilio/twilio-java

Tutte le issue di twilio/twilio-java

Issue simili

Altre issue su Java

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.