From fd02da8ff296a3a91bf0a5e4577373f916b36d5b Mon Sep 17 00:00:00 2001 From: Sebastian Hartte Date: Sat, 4 Jan 2025 13:40:00 +0100 Subject: [PATCH] Provide an extract of the response body in case of an error. --- .../runtime/downloads/DownloadManager.java | 32 ++++++++++++++++++- 1 file changed, 31 insertions(+), 1 deletion(-) diff --git a/src/main/java/net/neoforged/neoform/runtime/downloads/DownloadManager.java b/src/main/java/net/neoforged/neoform/runtime/downloads/DownloadManager.java index dd8d4be..279865d 100644 --- a/src/main/java/net/neoforged/neoform/runtime/downloads/DownloadManager.java +++ b/src/main/java/net/neoforged/neoform/runtime/downloads/DownloadManager.java @@ -10,6 +10,9 @@ import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.nio.ByteBuffer; +import java.nio.charset.CodingErrorAction; +import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; @@ -105,7 +108,7 @@ public boolean download(DownloadSpec spec, Path finalLocation, boolean silent) t } else if (response.statusCode() == 404) { throw new FileNotFoundException(url.toString()); } else { - lastError = new IOException("Failed to download " + url + ": HTTP Status Code " + response.statusCode()); + lastError = new IOException(buildRequestErrorMessage(url, response)); if (canRetryStatusCode(response.statusCode())) { waitForRetry(response); continue; @@ -145,6 +148,33 @@ public boolean download(DownloadSpec spec, Path finalLocation, boolean silent) t return true; } + private static String buildRequestErrorMessage(URI url, HttpResponse response) { + // Read the first kb of data from the file + String bodyDetails = ""; + try (var input = Files.newInputStream(response.body())) { + var decoder = StandardCharsets.UTF_8.newDecoder(); + decoder.onMalformedInput(CodingErrorAction.REPLACE); + decoder.onUnmappableCharacter(CodingErrorAction.REPLACE); + decoder.replaceWith("."); + bodyDetails = decoder.decode(ByteBuffer.wrap(input.readNBytes(1024))).toString(); + if (bodyDetails.contains(" response) throws IOException { // We only support the version of this that specifies the delay in seconds var retryAfter = response.headers().firstValueAsLong("Retry-After").orElse(5);