`RestException.fromJson` throws `ApiException` on non-JSON error responses instead of returning `null`
Nobody has claimed this yet.
Assessment
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Newbie friendliness
- 88/100
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
- Ships a Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from twilio/twilio-java
-
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
twilio/twilio-java#976 ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
twilio/twilio-java#975 ·
-
Difficulty 3/5 Half a day Newbie friendliness 62/100
twilio/twilio-java#989 ·
-
[BUG] Sip.Builder(String) drops SIP destinations with an explicit port when the scheme is omittedOpentype: bug
Difficulty 3/5 1-2 days Newbie friendliness 55/100
twilio/twilio-java#982 ·
-
Difficulty 5/5 Over a week Newbie friendliness 35/100
twilio/twilio-java#960 ·
All issues in twilio/twilio-java
Similar issues
-
Difficulty 2/5 1-3 hours Newbie friendliness 77/100
-
RegistryExceptionHandler uses self-referencing basePackageClasses instead of a controller classOpenbug finsim-registry good-first-issue
Difficulty 1/5 Under an hour Newbie friendliness 88/100
Maintainers usually reply within 1 day
-
status:pending type:bug
Difficulty 2/5 1-3 hours Newbie friendliness 75/100
-
bug level:trivial
Difficulty 2/5 1-3 hours Newbie friendliness 72/100
exoego/keycloak-fuhito#666 ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 79/100
hammy275/immersive-mc#669 ·