Skip to content

Commit 54b1a2e

Browse files
authored
Only try to parse Error if we get JSON content type (#555)
2 parents 9da20f4 + eaa6910 commit 54b1a2e

2 files changed

Lines changed: 12 additions & 2 deletions

File tree

src/main/java/land/oras/exception/OrasException.java

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
package land.oras.exception;
2222

2323
import land.oras.auth.HttpClient;
24+
import land.oras.utils.Const;
2425
import land.oras.utils.JsonUtils;
2526
import org.jspecify.annotations.NullMarked;
2627
import org.jspecify.annotations.Nullable;
@@ -62,9 +63,15 @@ public OrasException(String message) {
6263
*/
6364
public OrasException(HttpClient.ResponseWrapper<String> response) {
6465
this("Response code: " + response.statusCode());
66+
String contentType = response.headers().getOrDefault(Const.CONTENT_TYPE_HEADER, "");
6567
try {
6668
this.statusCode = response.statusCode();
67-
error = JsonUtils.fromJson(response.response(), Error.class);
69+
if (contentType.contains(Const.DEFAULT_JSON_MEDIA_TYPE)) {
70+
this.error = JsonUtils.fromJson(response.response(), Error.class);
71+
LOG.debug("Parsed error response: {}", error);
72+
} else {
73+
LOG.debug("Response content type is not JSON, cannot parse error response");
74+
}
6875
} catch (Exception e) {
6976
LOG.debug("Failed to parse error response", e);
7077
}

src/test/java/land/oras/exception/OrasExceptionTest.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626

2727
import java.util.Map;
2828
import land.oras.auth.HttpClient;
29+
import land.oras.utils.Const;
2930
import land.oras.utils.JsonUtils;
3031
import org.junit.jupiter.api.Test;
3132
import org.junit.jupiter.api.parallel.Execution;
@@ -47,7 +48,9 @@ void shouldWrapException() {
4748
@Test
4849
void shouldWrapResponse() {
4950
HttpClient.ResponseWrapper<String> response = new HttpClient.ResponseWrapper<>(
50-
JsonUtils.toJson(new Error("5001", "foo", "the details")), 500, Map.of());
51+
JsonUtils.toJson(new Error("5001", "foo", "the details")),
52+
500,
53+
Map.of(Const.CONTENT_TYPE_HEADER, Const.DEFAULT_JSON_MEDIA_TYPE));
5154
OrasException orasException = new OrasException(response);
5255

5356
// Getters

0 commit comments

Comments
 (0)