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

Open Beginner friendly
#988 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
88/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
java
Domain
api

Research direction

Read src/main/java/com/twilio/exception/RestException.java around fromJson, then review src/test/java/com/twilio/exception/RestExceptionTest.java and the callers' existing null checks. Run the RestException tests with malformed JSON and non-JSON response cases; done means both return null while valid JSON still deserializes and callers can use their existing no-content error path.

Written by the indexing model from the issue text.

Description

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

Dominant language
Java
Stars
528
Forks
462
Avg merge
2d 11h
Merged PRs (30d)
4

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from twilio/twilio-java

All issues in twilio/twilio-java

Similar issues

More Java issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.