diff --git a/QuickChart.php b/QuickChart.php index 21f95d3..88eadd8 100644 --- a/QuickChart.php +++ b/QuickChart.php @@ -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) {