refactor(core): remove unsafe type assertions in error utils (Phase 1.1) (#19750)

This commit is contained in:
matt korwel
2026-02-20 19:00:57 -06:00
committed by GitHub
parent 17a2b7fccf
commit cf450312a2
2 changed files with 86 additions and 16 deletions
+25 -5
View File
@@ -207,9 +207,13 @@ export function parseGoogleApiError(error: unknown): GoogleApiError | null {
detailObj['@type'] = detailObj[typeKey];
delete detailObj[typeKey];
}
// We can just cast it; the consumer will have to switch on @type
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
details.push(detailObj as unknown as GoogleApiErrorDetail);
// Basic structural check before casting.
// Since the proto definitions are loose, we primarily rely on @type presence.
if (typeof detailObj['@type'] === 'string') {
// We can just cast it; the consumer will have to switch on @type
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
details.push(detailObj as unknown as GoogleApiErrorDetail);
}
}
}
}
@@ -225,6 +229,16 @@ export function parseGoogleApiError(error: unknown): GoogleApiError | null {
return null;
}
function isErrorShape(obj: unknown): obj is ErrorShape {
return (
typeof obj === 'object' &&
obj !== null &&
(('message' in obj &&
typeof (obj as { message: unknown }).message === 'string') ||
('code' in obj && typeof (obj as { code: unknown }).code === 'number'))
);
}
function fromGaxiosError(errorObj: object): ErrorShape | undefined {
const gaxiosError = errorObj as {
response?: {
@@ -260,7 +274,10 @@ function fromGaxiosError(errorObj: object): ErrorShape | undefined {
if (typeof data === 'object' && data !== null) {
if ('error' in data) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
outerError = (data as { error: ErrorShape }).error;
const potentialError = (data as { error: unknown }).error;
if (isErrorShape(potentialError)) {
outerError = potentialError;
}
}
}
}
@@ -320,7 +337,10 @@ function fromApiError(errorObj: object): ErrorShape | undefined {
if (typeof data === 'object' && data !== null) {
if ('error' in data) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
outerError = (data as { error: ErrorShape }).error;
const potentialError = (data as { error: unknown }).error;
if (isErrorShape(potentialError)) {
outerError = potentialError;
}
}
}
}