Improve Auth error messaging (#1358)

This commit is contained in:
Tommaso Sciortino
2025-06-23 18:37:41 -07:00
committed by GitHub
parent 104f23da90
commit 0abd2a644e
9 changed files with 57 additions and 31 deletions

View File

@@ -4,6 +4,8 @@
* SPDX-License-Identifier: Apache-2.0
*/
import { GaxiosError } from 'gaxios';
export function isNodeError(error: unknown): error is NodeJS.ErrnoException {
return error instanceof Error && 'code' in error;
}
@@ -11,12 +13,50 @@ export function isNodeError(error: unknown): error is NodeJS.ErrnoException {
export function getErrorMessage(error: unknown): string {
if (error instanceof Error) {
return error.message;
} else {
try {
const errorMessage = String(error);
return errorMessage;
} catch {
return 'Failed to get error details';
}
}
try {
return String(error);
} catch {
return 'Failed to get error details';
}
}
export class ForbiddenError extends Error {}
export class UnauthorizedError extends Error {}
export class BadRequestError extends Error {}
interface ResponseData {
error?: {
code?: number;
message?: string;
};
}
export function toFriendlyError(error: unknown): unknown {
if (error instanceof GaxiosError) {
const data = parseResponseData(error);
if (data.error && data.error.message && data.error.code) {
switch (data.error.code) {
case 400:
return new BadRequestError(data.error.message);
case 401:
return new UnauthorizedError(data.error.message);
case 403:
// It's import to pass the message here since it might
// explain the cause like "the cloud project you're
// using doesn't have code assist enabled".
return new ForbiddenError(data.error.message);
default:
}
}
}
return error;
}
function parseResponseData(error: GaxiosError): ResponseData {
// Inexplicably, Gaxios sometimes doesn't JSONify the response data.
if (typeof error.response?.data === 'string') {
return JSON.parse(error.response?.data) as ResponseData;
}
return typeof error.response?.data as ResponseData;
}