@@ -219,6 +219,12 @@ function ($chunk) use (&$content, $listener) {
219219 }
220220
221221 if ($ response ->getStatusCode () >= 400 ) {
222+ if (! $ payload ['stream ' ]) {
223+ $ responseBody = $ response ->getBody ();
224+ $ json = is_string ($ responseBody ) ? json_decode ($ responseBody , true ) : null ;
225+ $ content = $ this ->formatErrorMessage ($ json );
226+ }
227+
222228 throw new \Exception (
223229 ucfirst ($ this ->getName ()).' API error: ' .$ content ,
224230 $ response ->getStatusCode ()
@@ -276,15 +282,10 @@ protected function process(Chunk $chunk, ?callable $listener): string
276282 continue ;
277283 }
278284
279- $ json = json_decode ($ line , true );
280- if (is_array ($ json ) && isset ($ json ['type ' ]) && $ json ['type ' ] === 'error ' ) {
281- $ type = $ json ['error ' ]['type ' ] ?? '' ;
282- $ message = $ json ['error ' ]['message ' ] ?? 'Unknown error ' ;
283-
284- return '( ' .$ type .') ' .$ message ;
285- }
285+ // Check if line starts with "data: " prefix and remove it, otherwise use the line as-is
286+ $ jsonString = str_starts_with ($ line , 'data: ' ) ? substr ($ line , 6 ) : $ line ;
287+ $ json = json_decode ($ jsonString , true );
286288
287- $ json = json_decode (substr ($ line , 6 ), true );
288289 if (! is_array ($ json )) {
289290 continue ;
290291 }
@@ -355,8 +356,7 @@ protected function process(Chunk $chunk, ?callable $listener): string
355356 break ;
356357
357358 case 'error ' :
358- $ errorMessage = isset ($ json ['error ' ]['message ' ]) ? (string ) $ json ['error ' ]['message ' ] : 'Unknown error ' ;
359- throw new \Exception ('Anthropic API error: ' .$ errorMessage );
359+ return $ this ->formatErrorMessage ($ json );
360360 }
361361 }
362362
@@ -439,4 +439,22 @@ public function getName(): string
439439 {
440440 return 'anthropic ' ;
441441 }
442+
443+ /**
444+ * Extract and format error information from API response
445+ *
446+ * @param mixed $json
447+ * @return string
448+ */
449+ protected function formatErrorMessage ($ json ): string
450+ {
451+ if (! is_array ($ json )) {
452+ return '(unknown_error) Unknown error ' ;
453+ }
454+
455+ $ errorType = isset ($ json ['error ' ]['type ' ]) ? (string ) $ json ['error ' ]['type ' ] : 'unknown_error ' ;
456+ $ errorMessage = isset ($ json ['error ' ]['message ' ]) ? (string ) $ json ['error ' ]['message ' ] : 'Unknown error ' ;
457+
458+ return '( ' .$ errorType .') ' .$ errorMessage ;
459+ }
442460}
0 commit comments