refactor(ai-chat)!: unify provider error formatting via describeProviderError

Behaviour change (split out of the test commit per review, and now covered).

Both the stream onError log line and the error text streamed to the client were
formatted by separate inline blocks that only emitted "<status>: <message>".
Route both through the shared describeProviderError() so formatting stays in one
place.

BEHAVIOUR CHANGE: describeProviderError additionally appends a single-line,
300-char-truncated snippet of the provider responseBody/text. So the log line
AND the user-facing stream error now include that snippet (e.g. the HTML error
page from a misconfigured endpoint), which previously neither did. This is
intentional — it makes a misconfigured external endpoint diagnosable — and is
safe: the API key travels in the Authorization header and is never echoed in
the response body (see the util's docstring). A `fallback` param is added so
each call site keeps its own default ('AI stream error' for the stream).

Adds ai-error.util.spec.ts covering the formatter, including the appended /
truncated body snippet, so this behaviour is no longer untested.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
claude code agent 227
2026-06-20 17:59:55 +03:00
committed by vvzvlad
parent 1e650262a4
commit cedea4072b
3 changed files with 80 additions and 18 deletions
@@ -9,10 +9,16 @@
*
* None of these fields contain the API key (it is sent as an Authorization
* header and never echoed in the response body), so this is safe to log/return.
*
* `fallback` is used when the error carries no usable message (e.g. a bare
* object); defaults to 'Unknown error'.
*/
export function describeProviderError(err: unknown): string {
export function describeProviderError(
err: unknown,
fallback = 'Unknown error',
): string {
if (typeof err !== 'object' || err === null) {
return typeof err === 'string' ? err : 'Unknown error';
return typeof err === 'string' && err ? err : fallback;
}
const e = err as {
statusCode?: number;
@@ -23,7 +29,7 @@ export function describeProviderError(err: unknown): string {
const base =
typeof e.statusCode === 'number'
? `${e.statusCode}: ${e.message ?? ''}`.trim()
: (e.message ?? 'Unknown error');
: (e.message ?? fallback);
const body = (e.responseBody ?? e.text ?? '').trim();
if (!body) return base;
// Collapse whitespace so a multi-line HTML body stays on one log line.