Skip to content

Commit

Permalink
fix: throw exception on non-2xx response (#13)
Browse files Browse the repository at this point in the history
  • Loading branch information
typpo authored Dec 27, 2023
1 parent 33d62e1 commit afdcc10
Showing 1 changed file with 30 additions and 2 deletions.
32 changes: 30 additions & 2 deletions QuickChart.php
Original file line number Diff line number Diff line change
Expand Up @@ -146,11 +146,39 @@ function toBinary() {
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($result === false) {
throw new ErrorException(curl_error($ch));
$error = curl_error($ch);
curl_close($ch);
throw new Exception("Curl error: $error");
}

curl_close($ch);
return $result;

if ($httpStatusCode >= 200 && $httpStatusCode < 300) {
return $result;
}

// Parse response headers
$responseHeaders = [];
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headerStr = substr($result, 0, $headerSize);
foreach (explode("\r\n", $headerStr) as $i => $line) {
if ($i === 0) {
$responseHeaders['http_code'] = $line;
} else {
list($key, $value) = explode(': ', $line);
$responseHeaders[$key] = $value;
}
}

$errorHeader = isset($responseHeaders['X-quickchart-error']) ? $responseHeaders['X-quickchart-error'] : null;
if ($errorHeader) {
throw new Exception("QuickChart API returned an error with status code: $httpStatusCode. Error: $errorHeader");
}

throw new Exception("QuickChart API returned an error with status code: $httpStatusCode. Response: $result");
}

function toFile($path) {
Expand Down

0 comments on commit afdcc10

Please sign in to comment.