Skip to content

Commit afdcc10

Browse files
authored
fix: throw exception on non-2xx response (#13)
1 parent 33d62e1 commit afdcc10

1 file changed

Lines changed: 30 additions & 2 deletions

File tree

QuickChart.php

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -146,11 +146,39 @@ function toBinary() {
146146
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
147147
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
148148
$result = curl_exec($ch);
149+
$httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
150+
149151
if ($result === false) {
150-
throw new ErrorException(curl_error($ch));
152+
$error = curl_error($ch);
153+
curl_close($ch);
154+
throw new Exception("Curl error: $error");
151155
}
156+
152157
curl_close($ch);
153-
return $result;
158+
159+
if ($httpStatusCode >= 200 && $httpStatusCode < 300) {
160+
return $result;
161+
}
162+
163+
// Parse response headers
164+
$responseHeaders = [];
165+
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
166+
$headerStr = substr($result, 0, $headerSize);
167+
foreach (explode("\r\n", $headerStr) as $i => $line) {
168+
if ($i === 0) {
169+
$responseHeaders['http_code'] = $line;
170+
} else {
171+
list($key, $value) = explode(': ', $line);
172+
$responseHeaders[$key] = $value;
173+
}
174+
}
175+
176+
$errorHeader = isset($responseHeaders['X-quickchart-error']) ? $responseHeaders['X-quickchart-error'] : null;
177+
if ($errorHeader) {
178+
throw new Exception("QuickChart API returned an error with status code: $httpStatusCode. Error: $errorHeader");
179+
}
180+
181+
throw new Exception("QuickChart API returned an error with status code: $httpStatusCode. Response: $result");
154182
}
155183

156184
function toFile($path) {

0 commit comments

Comments
 (0)