`RestException.fromJson` throws `ApiException` on non-JSON error responses instead of returning `null`
Chưa có ai nhận issue này.
Đánh giá
- Độ khó
- 2/5
- Thời gian dự kiến
- 1-3 giờ
- Mức phù hợp với người mới
- 88/100
Hướng nghiên cứu
Đọc src/main/java/com/twilio/exception/RestException.java ở phần quanh fromJson, sau đó xem lại src/test/java/com/twilio/exception/RestExceptionTest.java và các kiểm tra null hiện có ở phía gọi. Chạy các bài kiểm tra RestException với JSON sai định dạng và các trường hợp phản hồi không phải JSON; hoàn thành khi cả hai đều trả về null, JSON hợp lệ vẫn được giải tuần tự và phía gọi có thể sử dụng luồng xử lý lỗi không có nội dung hiện tại.
Do mô hình lập chỉ mục viết ra từ nội dung của issue.
Mô tả
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
- Ngôn ngữ chính
- Java
- Star
- 528
- Fork
- 462
- Merge trung bình
- 2 ngày 11 giờ
- Pull request đã merge (30 ngày)
- 4
Chuẩn bị môi trường
- Có Dockerfile hoặc tệp Docker Compose
- Có mẫu pull request
- Đọc hướng dẫn đóng góp
Bắt đầu từ đâu
- Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
- Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
- Fork repository và làm thay đổi trên một nhánh.
- Mở pull request có tham chiếu số hiệu của issue.
Issue khác của twilio/twilio-java
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 68/100
twilio/twilio-java#976 ·
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 88/100
twilio/twilio-java#975 ·
-
Độ khó 3/5 Nửa ngày Mức phù hợp với người mới 62/100
twilio/twilio-java#989 ·
-
[BUG] Sip.Builder(String) drops SIP destinations with an explicit port when the scheme is omittedĐang mởtype: bug
Độ khó 3/5 1-2 ngày Mức phù hợp với người mới 55/100
twilio/twilio-java#982 ·
-
Độ khó 5/5 Hơn một tuần Mức phù hợp với người mới 35/100
twilio/twilio-java#960 ·
Tất cả issue của twilio/twilio-java
Issue tương tự
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 77/100
-
RegistryExceptionHandler uses self-referencing basePackageClasses instead of a controller classĐang mởbug finsim-registry good-first-issue
Độ khó 1/5 Dưới một giờ Mức phù hợp với người mới 88/100
Maintainer thường phản hồi trong vòng 1 ngày
-
status:pending type:bug
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 75/100
-
A CSV row that removes a language with #CLEAR and fills another name of it keeps one of themĐang mởbug level:trivial
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 72/100
exoego/keycloak-fuhito#666 ·
Maintainer thường phản hồi trong vòng 1 ngày
-
Độ khó 2/5 1-3 giờ Mức phù hợp với người mới 79/100
hammy275/immersive-mc#669 ·