Skip to content

Commit 9ad830f

Browse files
authored
feat(gax): add error attributes for error logging (#9743)
This PR adds helpers that resolve the `gcp.errors.domain` and `gcp.errors.metadata.*` attributes. ### Key Changes: - Move the ErrorInfo lookup in `resolveErrorInfoReason` into a shared private helper (no behavior change). - Add `resolveErrorInfoDomain` for `gcp.errors.domain`. - Add `resolveErrorInfoMetadataAttributes`, which flattens ErrorInfo metadata into `gcp.errors.metadata.<key>` attributes, using only the first ErrorInfo metadata found. - Added unit tests for both helpers, including real HTTP and gRPC `GoogleError`s.
1 parent 6189515 commit 9ad830f

5 files changed

Lines changed: 807 additions & 64 deletions

File tree

‎core/packages/gax/src/fallbackServiceStub.ts‎

Lines changed: 122 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,9 @@ interface CallOutcome {
121121
* HTTP status number, so it never matches a retry code and is silently treated
122122
* as a permanent failure.
123123
*
124-
* An error carrying an HTTP status maps through `rpcCodeFromHttpStatusCode`.
124+
* An error carrying an HTTP status maps through `rpcCodeFromHttpStatusCode`,
125+
* decoding a structured Google HTTP error payload when present so `ErrorInfo`
126+
* and `statusDetails` are promoted for rejected 401 and 403 responses.
125127
* Otherwise the call failed before producing a response, which is reported as
126128
* UNAVAILABLE, except for an explicit cancellation (CANCELLED) or an elapsed
127129
* deadline (DEADLINE_EXCEEDED).
@@ -131,6 +133,107 @@ interface CallOutcome {
131133
* @returns A GoogleError with a numeric `code`, or the original value if it is
132134
* not an Error.
133135
*/
136+
function _isPlainObject(value: unknown): value is Record<string, unknown> {
137+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
138+
return false;
139+
}
140+
const proto = Object.getPrototypeOf(value);
141+
return proto === Object.prototype || proto === null;
142+
}
143+
144+
function _isGoogleErrorStatusObject(value: unknown, wrapped: boolean): boolean {
145+
if (!_isPlainObject(value)) {
146+
return false;
147+
}
148+
const hasProtoDetails =
149+
Array.isArray(value.details) &&
150+
value.details.some(
151+
detail => _isPlainObject(detail) && typeof detail['@type'] === 'string',
152+
);
153+
if (hasProtoDetails) {
154+
return true;
155+
}
156+
if (typeof value.message === 'string') {
157+
return (
158+
wrapped ||
159+
value.code === undefined ||
160+
(typeof value.code === 'number' && value.code >= 100 && value.code < 600)
161+
);
162+
}
163+
return (
164+
wrapped &&
165+
(typeof value.status === 'string' ||
166+
typeof value.code === 'number' ||
167+
Array.isArray(value.details))
168+
);
169+
}
170+
171+
/**
172+
* Checks whether a decoded JSON value has the structure of a Google HTTP error
173+
* payload accepted by {@link GoogleError.parseHttpError} (standard
174+
* `{error: {...}}`, streaming `[{error: {...}}]`, or an unwrapped status
175+
* object). Guarding before `parseHttpError` prevents non-Google JSON payloads
176+
* (such as `{}` or OAuth `{"error": "invalid_token"}`) from discarding the
177+
* fallback error message or HTTP status mapping.
178+
*/
179+
function _isHttpErrorPayload(json: unknown): boolean {
180+
if (Array.isArray(json)) {
181+
const entry = json.find(item => _isPlainObject(item) && 'error' in item);
182+
return entry !== undefined && _isGoogleErrorStatusObject(entry.error, true);
183+
}
184+
if (!_isPlainObject(json)) {
185+
return false;
186+
}
187+
if ('error' in json) {
188+
return _isGoogleErrorStatusObject(json.error, true);
189+
}
190+
return _isGoogleErrorStatusObject(json, false);
191+
}
192+
193+
/**
194+
* Attempts to decode a structured Google HTTP error (`ErrorInfo`,
195+
* `statusDetails`, message, and canonical status) from a rejected fetch error.
196+
*
197+
* With `responseType: 'stream'`, gaxios drains rejected 401/403 bodies as UTF-8
198+
* text into `err.message`, while `response.data` may be `undefined`, redacted,
199+
* or pre-parsed depending on the fetch implementation or adapter.
200+
*/
201+
function _parseHttpErrorFromRejection(
202+
err: Error,
203+
responseData: unknown,
204+
): GoogleError | undefined {
205+
for (const candidate of [responseData, err.message]) {
206+
let json: unknown;
207+
if (typeof candidate === 'string') {
208+
try {
209+
json = JSON.parse(candidate);
210+
} catch {
211+
continue;
212+
}
213+
} else if (_isHttpErrorPayload(candidate)) {
214+
try {
215+
// `GoogleError.parseHttpError` mutates its input in place.
216+
json = JSON.parse(JSON.stringify(candidate));
217+
} catch {
218+
continue;
219+
}
220+
} else {
221+
continue;
222+
}
223+
224+
if (!_isHttpErrorPayload(json)) {
225+
continue;
226+
}
227+
228+
try {
229+
return GoogleError.parseHttpError(json);
230+
} catch {
231+
// Fall through to the next candidate or raw status mapping.
232+
}
233+
}
234+
return undefined;
235+
}
236+
134237
function _toGoogleError(err: unknown, outcome: CallOutcome): unknown {
135238
if (err instanceof GoogleError) {
136239
return err;
@@ -146,24 +249,29 @@ function _toGoogleError(err: unknown, outcome: CallOutcome): unknown {
146249
// error instance originating from any particular copy of gaxios.
147250
const fetchError = err as Partial<{
148251
status: number;
149-
response: {status?: number};
252+
response: {status?: number; data?: unknown};
150253
code: string | number;
151254
}>;
152255

153-
// Errors that carry an HTTP status map through the standard HTTP-to-gRPC
154-
// table. Checked first: a response arrived, so it outranks the abort
155-
// bookkeeping below. The received status is also kept as-is, because the
156-
// table is lossy — it collapses whole ranges — and this is the only place it
157-
// can be recorded for a 401 or a 403, which `validateStatus` rejects on
158-
// purpose (see below) and which therefore never reach the decoder.
256+
// Errors that carry an HTTP status arrive here when `validateStatus` rejects
257+
// them (401 and 403; see below), bypassing `decodeResponse`. Checked first: a
258+
// response arrived, so it outranks the abort bookkeeping below. Decode a JSON
259+
// Google error payload when present so `ErrorInfo` and `statusDetails` are
260+
// promoted onto the `GoogleError`, and always preserve the received status
261+
// because the HTTP-to-gRPC table is lossy — it collapses whole ranges.
159262
const httpStatus =
160263
typeof fetchError.status === 'number'
161264
? fetchError.status
162265
: fetchError.response?.status;
163266
if (typeof httpStatus === 'number') {
164-
error.code = rpcCodeFromHttpStatusCode(httpStatus);
165-
error.httpStatusCode = httpStatus;
166-
return error;
267+
const parsedError =
268+
_parseHttpErrorFromRejection(err, fetchError.response?.data) ?? error;
269+
parsedError.cause = err;
270+
if (typeof parsedError.code !== 'number') {
271+
parsedError.code = rpcCodeFromHttpStatusCode(httpStatus);
272+
}
273+
parsedError.httpStatusCode = httpStatus;
274+
return parsedError;
167275
}
168276

169277
// An explicit cancellation and an elapsed deadline are distinct conditions in
@@ -392,12 +500,9 @@ export function generateServiceStub(
392500
responseType: 'stream', // ensure gaxios returns the data directly so that it handle data/streams itself
393501
// Error responses must resolve so that they are decoded below into a
394502
// GoogleError carrying a gRPC status code. 401 and 403 keep rejecting
395-
// so that the auth client can refresh credentials and retry.
396-
//
397-
// Those two therefore never reach the decoder: they are mapped from the
398-
// HTTP status alone, so an ErrorInfo or statusDetails payload in a 401
399-
// or 403 body is not promoted onto the error the way it is for every
400-
// other failing status.
503+
// so that the auth client can refresh credentials and retry; if they
504+
// still fail, `_toGoogleError` decodes their error payload off the
505+
// rejection.
401506
validateStatus: (status: number) => status !== 401 && status !== 403,
402507
agent: agentOption || undefined,
403508
};

0 commit comments

Comments
 (0)