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

Abierto Apto para principiantes
#988 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
2/5
Tiempo estimado
1-3 horas
Aptitud para principiantes
88/100
Tipo de issue
Error
Claridad
Bien especificado
Estado de actividad
Activo
Stack tecnológico
java
Área
api

Línea de trabajo

Lee src/main/java/com/twilio/exception/RestException.java en torno a fromJson y luego revisa src/test/java/com/twilio/exception/RestExceptionTest.java y las comprobaciones de null existentes en los llamadores. Ejecuta las pruebas de RestException con JSON malformado y casos de respuestas que no sean JSON; el objetivo se cumple cuando ambos devuelven null, el JSON válido sigue deserializándose y los llamadores pueden usar su ruta de error existente para contenido ausente.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

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

Lenguaje dominante
Java
Estrellas
528
Forks
462
Merge medio
2 d 11 h
PR fusionados (30 d)
4

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de twilio/twilio-java

Todos los issues de twilio/twilio-java

Issues similares

Más issues de Java

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.