From cb4c3f082e8767b70fc607584354f4b70d92100b Mon Sep 17 00:00:00 2001 From: jdalton Date: Tue, 24 Nov 2026 21:05:43 -0500 Subject: [PATCH] refactor(cli): consolidate error message handling --- src/commands/fix/coana-fix.mts | 6 ++---- src/commands/logout/attempt-logout.mts | 4 ++-- src/commands/logout/attempt-logout.test.mts | 2 +- src/commands/manifest/bazel/cleanup.mts | 10 +++++----- .../manifest/bazel/extract_bazel_to_maven.mts | 12 ++++++------ .../manifest/bazel/extract_bazel_to_pypi.mts | 4 ++-- .../manifest/bazel/output-base-check.mts | 4 ++-- src/commands/manifest/bazel/pypi-discovery.mts | 4 ++-- src/commands/manifest/convert_sbt_to_maven.mts | 4 ++-- src/commands/wrapper/postinstall-wrapper.mts | 4 ++-- src/sea/build-sea.mts | 4 ++-- src/sea/download-bytes.mts | 6 ++---- src/sea/stage/coana.mts | 5 +++-- src/utils/api.mts | 10 +++++----- src/utils/api.test.mts | 2 +- src/utils/coana/release.mts | 8 ++++---- src/utils/config.mts | 4 ++-- src/utils/cve-to-ghsa.mts | 4 ++-- src/utils/errors.mts | 10 +++++----- src/utils/errors.test.mts | 16 ++++++++-------- src/utils/purl-to-ghsa.mts | 4 ++-- src/utils/sdk.mts | 4 ++-- src/utils/sdk.test.mts | 2 +- 23 files changed, 65 insertions(+), 68 deletions(-) diff --git a/src/commands/fix/coana-fix.mts b/src/commands/fix/coana-fix.mts index bc3a3d303b..08528e9909 100644 --- a/src/commands/fix/coana-fix.mts +++ b/src/commands/fix/coana-fix.mts @@ -30,7 +30,7 @@ import { } from '../../utils/coana.mts' import { findSocketYmlSync } from '../../utils/config.mts' import { debugDir, debugFn } from '../../utils/debug.mts' -import { getErrorCause } from '../../utils/errors.mts' +import { errorMessage } from '../../utils/errors.mts' import { readJsonSync, withTmpDir } from '../../utils/fs.mts' import { gitCheckoutBranch, @@ -763,9 +763,7 @@ async function coanaFixWithFacts( } } else if (!fixCResult.ok) { if (!silence) { - logger.error( - `Update failed for ${ghsaId}: ${getErrorCause(fixCResult)}`, - ) + logger.error(`Update failed for ${ghsaId}: ${errorMessage(fixCResult)}`) } // Clean up temp file on failure. try { diff --git a/src/commands/logout/attempt-logout.mts b/src/commands/logout/attempt-logout.mts index 74385005fb..b234a93dc5 100644 --- a/src/commands/logout/attempt-logout.mts +++ b/src/commands/logout/attempt-logout.mts @@ -1,7 +1,7 @@ import { applyLogout } from './apply-logout.mts' import constants from '../../constants.mts' import { isConfigFromFlag } from '../../utils/config.mts' -import { getErrorCause } from '../../utils/errors.mts' +import { errorMessage } from '../../utils/errors.mts' import { logger } from '../../utils/logger.mts' import { logoutOAuth } from '../../utils/oauth.mts' import { getDefaultProxyUrl } from '../../utils/sdk.mts' @@ -37,6 +37,6 @@ export async function attemptLogout() { } } catch (error) { logger.fail('Failed to complete logout steps') - logger.warn(getErrorCause(error)) + logger.warn(errorMessage(error)) } } diff --git a/src/commands/logout/attempt-logout.test.mts b/src/commands/logout/attempt-logout.test.mts index a9d1c13bdd..17636ebd21 100644 --- a/src/commands/logout/attempt-logout.test.mts +++ b/src/commands/logout/attempt-logout.test.mts @@ -23,7 +23,7 @@ vi.mock('../../utils/config.mts', () => ({ isConfigFromFlag: mockIsConfigFromFlag, })) vi.mock('../../utils/errors.mts', () => ({ - getErrorCause: (error: unknown) => + errorMessage: (error: unknown) => error instanceof Error ? error.message : 'Unknown error', })) vi.mock('../../utils/oauth.mts', () => ({ logoutOAuth: mockLogoutOAuth })) diff --git a/src/commands/manifest/bazel/cleanup.mts b/src/commands/manifest/bazel/cleanup.mts index ec55032f40..b5ca9732e7 100644 --- a/src/commands/manifest/bazel/cleanup.mts +++ b/src/commands/manifest/bazel/cleanup.mts @@ -16,7 +16,7 @@ import { getBazelEnvironmentValue, spawnBazel, } from './process.mts' -import { getErrorCause, isErrnoException } from '../../../utils/errors.mts' +import { errorMessage, isErrnoException } from '../../../utils/errors.mts' import { logger } from '../../../utils/logger.mts' import type { BazelQueryOptions } from './query-runner.mts' @@ -54,7 +54,7 @@ export async function removeBazelTempdir(dir: string): Promise { return true } catch (error) { logger.warn( - `Bazel temporary directory could not be removed: ${dir}. ${getErrorCause(error)}`, + `Bazel temporary directory could not be removed: ${dir}. ${errorMessage(error)}`, ) return false } @@ -105,7 +105,7 @@ export async function cleanUpBazelOutputRoot( listed = findServerPids(root) } catch (e) { logger.warn( - `Bazel output root kept because its servers could not be checked: ${root}. ${getErrorCause(e)}`, + `Bazel output root kept because its servers could not be checked: ${root}. ${errorMessage(e)}`, ) } const servers = new Set(listed) @@ -168,7 +168,7 @@ export async function shutDownBazelServer( pid = readServerPid(outputBase) await spawnBazel(opts.bin, [...startupFlags, 'shutdown'], spawnOptions) } catch (error) { - logger.warn(`Bazel shutdown failed in ${opts.cwd}. ${getErrorCause(error)}`) + logger.warn(`Bazel shutdown failed in ${opts.cwd}. ${errorMessage(error)}`) } return pid } @@ -240,7 +240,7 @@ async function stopBazelServer(pid: number): Promise { } catch (e) { if (!isErrnoException(e) || e.code !== 'ESRCH') { logger.warn( - `Bazel server ${pid} could not be stopped. ${getErrorCause(e)}`, + `Bazel server ${pid} could not be stopped. ${errorMessage(e)}`, ) return false } diff --git a/src/commands/manifest/bazel/extract_bazel_to_maven.mts b/src/commands/manifest/bazel/extract_bazel_to_maven.mts index 92c248c8c4..4c8772e918 100644 --- a/src/commands/manifest/bazel/extract_bazel_to_maven.mts +++ b/src/commands/manifest/bazel/extract_bazel_to_maven.mts @@ -34,7 +34,7 @@ import { getBazelInvocationFlags, } from './workspace-detect.mts' import { findWorkspaceRoots } from './workspace-walk.mts' -import { getErrorCause } from '../../../utils/errors.mts' +import { errorMessage } from '../../../utils/errors.mts' import { IGNORED_DIRS } from '../../../utils/glob.mts' import { logger } from '../../../utils/logger.mts' @@ -430,7 +430,7 @@ async function writeCompletenessSummary(args: { } catch (e) { if (verbose) { logger.log( - `[VERBOSE] completeness summary not written (${getErrorCause(e)}); the run result still carries the signal`, + `[VERBOSE] completeness summary not written (${errorMessage(e)}); the run result still carries the signal`, ) } } @@ -676,7 +676,7 @@ export async function extractBazelToMaven( if (pythonShimDir) { await removeBazelTempdir(pythonShimDir) } - logger.fail(`Unexpected error in bazel2maven: ${getErrorCause(e)}`) + logger.fail(`Unexpected error in bazel2maven: ${errorMessage(e)}`) if (verbose) { logger.group('[VERBOSE] error:') logger.log(e) @@ -772,7 +772,7 @@ export async function extractBazelToMaven( // here": record it so the run is flagged not-complete (a hard failure // when nothing else was analyzable, partial otherwise) rather than // silently skipped. - const reason = getErrorCause(e) + const reason = errorMessage(e) if (verbose) { logger.log( `[VERBOSE] workspace ${workspaceRoot}: load failed (${reason})`, @@ -959,7 +959,7 @@ export async function extractBazelToMaven( // Best-effort per hub: a write failure must not abort the walk and // discard the manifests other hubs already produced. logger.warn( - `@${repoName}: failed to write manifest (${getErrorCause(e)}); skipping this hub`, + `@${repoName}: failed to write manifest (${errorMessage(e)}); skipping this hub`, ) hubsFailed += 1 hubOutcomes.push({ @@ -1162,7 +1162,7 @@ export async function extractBazelToMaven( workspaceOutcomes, } } catch (e) { - logger.fail(`Unexpected error in bazel2maven: ${getErrorCause(e)}`) + logger.fail(`Unexpected error in bazel2maven: ${errorMessage(e)}`) if (verbose) { logger.group('[VERBOSE] error:') logger.log(e) diff --git a/src/commands/manifest/bazel/extract_bazel_to_pypi.mts b/src/commands/manifest/bazel/extract_bazel_to_pypi.mts index cb16b84885..d91d23644a 100644 --- a/src/commands/manifest/bazel/extract_bazel_to_pypi.mts +++ b/src/commands/manifest/bazel/extract_bazel_to_pypi.mts @@ -31,7 +31,7 @@ import { detectWorkspaceMode, getBazelInvocationFlags, } from './workspace-detect.mts' -import { InputError, getErrorCause } from '../../../utils/errors.mts' +import { InputError, errorMessage } from '../../../utils/errors.mts' import { logger } from '../../../utils/logger.mts' import type { PypiHubCandidate } from './pypi-discovery.mts' @@ -298,7 +298,7 @@ export async function extractBazelToPypi( ok: true, } } catch (e) { - logger.fail(`Unexpected error in bazel2pypi: ${getErrorCause(e)}`) + logger.fail(`Unexpected error in bazel2pypi: ${errorMessage(e)}`) if (verbose) { logger.group('[VERBOSE] error:') logger.log(e) diff --git a/src/commands/manifest/bazel/output-base-check.mts b/src/commands/manifest/bazel/output-base-check.mts index 4afbc9f70c..75b2c224df 100644 --- a/src/commands/manifest/bazel/output-base-check.mts +++ b/src/commands/manifest/bazel/output-base-check.mts @@ -6,7 +6,7 @@ import { } from 'node:fs' import path from 'node:path' -import { InputError, getErrorCause } from '../../../utils/errors.mts' +import { InputError, errorMessage } from '../../../utils/errors.mts' // Validates that --bazel-output-base is a path we can use as Bazel's output_base. // Throws InputError if: @@ -40,7 +40,7 @@ export function validateOutputBase(outputBase: string, cwd: string): void { mkdirSync(resolved, { recursive: true }) } catch (e) { throw new InputError( - `--bazel-output-base could not be created at ${resolved}: ${getErrorCause(e)}`, + `--bazel-output-base could not be created at ${resolved}: ${errorMessage(e)}`, ) } } diff --git a/src/commands/manifest/bazel/pypi-discovery.mts b/src/commands/manifest/bazel/pypi-discovery.mts index c9600266a9..a1f52b7505 100644 --- a/src/commands/manifest/bazel/pypi-discovery.mts +++ b/src/commands/manifest/bazel/pypi-discovery.mts @@ -1,7 +1,7 @@ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs' import path from 'node:path' -import { getErrorCause } from '../../../utils/errors.mts' +import { errorMessage } from '../../../utils/errors.mts' import { logger } from '../../../utils/logger.mts' import type { RepoProbe } from './repo-discovery.mts' @@ -449,7 +449,7 @@ export async function validatePypiHub( if (verbose) { logger.log( `[VERBOSE] discovery: probe @${hubName}: REJECT (probe threw):`, - getErrorCause(e), + errorMessage(e), ) } return { valid: false, stdout: '' } diff --git a/src/commands/manifest/convert_sbt_to_maven.mts b/src/commands/manifest/convert_sbt_to_maven.mts index 7d28830b70..7cf4dffb19 100644 --- a/src/commands/manifest/convert_sbt_to_maven.mts +++ b/src/commands/manifest/convert_sbt_to_maven.mts @@ -4,7 +4,7 @@ import path from 'node:path' import constants from '../../constants.mts' import { resolveBuildToolBin } from './scripts/build-tool.mts' import { isStandaloneSea } from '../../sea/runtime.mts' -import { getErrorCause } from '../../utils/errors.mts' +import { errorMessage } from '../../utils/errors.mts' import { safeReadFile } from '../../utils/fs.mts' import { logger } from '../../utils/logger.mts' import { spawn } from '../../utils/spawn.mts' @@ -154,7 +154,7 @@ export async function convertSbtToMaven({ copied.push(destPath) } catch (e) { logger.warn( - `Failed to copy \`${pomPath}\` to \`${destPath}\`: ${getErrorCause(e)}`, + `Failed to copy \`${pomPath}\` to \`${destPath}\`: ${errorMessage(e)}`, ) } } diff --git a/src/commands/wrapper/postinstall-wrapper.mts b/src/commands/wrapper/postinstall-wrapper.mts index 4097444054..0a389847c1 100644 --- a/src/commands/wrapper/postinstall-wrapper.mts +++ b/src/commands/wrapper/postinstall-wrapper.mts @@ -5,7 +5,7 @@ import { checkSocketWrapperSetup } from './check-socket-wrapper-setup.mts' import constants from '../../constants.mts' import { getBashrcDetails } from '../../utils/completion.mts' import { debugDir, debugFn } from '../../utils/debug.mts' -import { getErrorCause } from '../../utils/errors.mts' +import { errorMessage } from '../../utils/errors.mts' import { logger } from '../../utils/logger.mts' import { confirm } from '../../utils/prompts.mts' import { updateInstalledTabCompletionScript } from '../install/setup-tab-completion.mts' @@ -82,7 +82,7 @@ async function setupShadowNpm(query: string): Promise { } } catch (e) { throw new Error( - `There was an issue setting up the alias: ${getErrorCause(e)}`, + `There was an issue setting up the alias: ${errorMessage(e)}`, ) } } diff --git a/src/sea/build-sea.mts b/src/sea/build-sea.mts index ab2fbf3e0e..16dd2021de 100644 --- a/src/sea/build-sea.mts +++ b/src/sea/build-sea.mts @@ -23,7 +23,7 @@ import { stageSynp } from './stage/synp.mts' import { stageUv } from './stage/uv.mts' import { SEA_VERSION } from './version.mts' import { digestVfs } from './vfs-digest.mts' -import { getErrorCause } from '../utils/errors.mts' +import { errorMessage } from '../utils/errors.mts' import { quotePowerShell } from '../utils/quote-powershell.mts' const SEA_DIRECTORY = path.dirname(fileURLToPath(import.meta.url)) @@ -985,7 +985,7 @@ async function main(): Promise { } return [ new Error( - `SEA preparation failed: ${prepLabels[index]}: ${getErrorCause(result.reason)}`, + `SEA preparation failed: ${prepLabels[index]}: ${errorMessage(result.reason)}`, { cause: result.reason }, ), ] diff --git a/src/sea/download-bytes.mts b/src/sea/download-bytes.mts index 35aac4ca64..69c66da94d 100644 --- a/src/sea/download-bytes.mts +++ b/src/sea/download-bytes.mts @@ -1,4 +1,6 @@ /* eslint-disable no-await-in-loop -- Retry attempts must run sequentially. */ +import { errorMessage } from '../utils/errors.mts' + const MAX_ATTEMPTS = 3 const RETRY_DELAYS = [500, 1_000] as const const RETRYABLE_HTTP_STATUSES = new Set([408, 429, 500, 502, 503, 504]) @@ -22,10 +24,6 @@ type DownloadBytesOptions = { acceptedStatuses?: readonly number[] | undefined } -export function errorMessage(error: unknown): string { - return error instanceof Error ? error.message : String(error) -} - export function isRetryable(error: unknown): boolean { const seen = new Set() let current: unknown = error diff --git a/src/sea/stage/coana.mts b/src/sea/stage/coana.mts index 2822fb9a2f..a3c7f6222b 100644 --- a/src/sea/stage/coana.mts +++ b/src/sea/stage/coana.mts @@ -11,6 +11,7 @@ import { getDefaultOrgSlug } from '../../commands/ci/fetch-default-org-slug.mts' import { COANA_CLI_VERSION } from '../../constants.mts' import { apiFetch, sendApiRequest } from '../../utils/api.mts' import { envAsBoolean } from '../../utils/env.mts' +import { errorMessage } from '../../utils/errors.mts' import { SEA_COANA_VFS_PATHS, seaCoanaPaths } from '../paths/coana.mts' const COMPONENTS = ['analyzers', 'cli'] as const @@ -91,7 +92,7 @@ async function fetchArtifacts(org: string): Promise { ) if (!result.ok) { throw new Error( - `the Socket API denied Coana artifact access: ${result.message}${result.cause ? ` (${result.cause})` : ''}`, + result.cause ? `${result.message} (${result.cause})` : result.message, ) } return parseArtifacts(result.data) @@ -228,7 +229,7 @@ export async function stageCoana( artifacts = await fetchArtifacts(org.data) } catch (error) { throw new Error( - `Coana ${COANA_CLI_VERSION} download failed for ${org.data}. Where: Socket API artifact access. Saw: ${error instanceof Error ? error.message : String(error)}; wanted: the pinned CLI and analyzer artifacts. Fix: ensure SOCKET_API_TOKEN_FOR_CLI_AND_SFW can access Coana reachability artifacts for this organization, then retry the 2.x RC build.`, + `Could not fetch Coana ${COANA_CLI_VERSION} artifacts for ${org.data}: ${errorMessage(error)}. Check that the build token can access Coana artifacts for this organization.`, { cause: error }, ) } diff --git a/src/utils/api.mts b/src/utils/api.mts index 3078ab5816..8c169a250f 100644 --- a/src/utils/api.mts +++ b/src/utils/api.mts @@ -32,7 +32,7 @@ import { debugDir, debugFn, } from './debug.mts' -import { getErrorCause, isErrnoException } from './errors.mts' +import { errorMessage, isErrnoException } from './errors.mts' import { logger } from './logger.mts' import { getRequirements, getRequirementsKey } from './requirements.mts' import { @@ -658,7 +658,7 @@ export async function queryApiSafeTextWithStatus( return { ok: false, message: 'Authentication Error', - cause: getErrorCause(error), + cause: errorMessage(error), } } if (!apiToken) { @@ -751,7 +751,7 @@ export async function queryApiSafeTextWithStatus( const cause = isErrnoException(e) && e.code === 'ETIMEDOUT' - ? `${getErrorCause(e)} (path: ${path})` + ? `${errorMessage(e)} (path: ${path})` : `Unexpected error reading response text (path: ${path})` return { @@ -827,7 +827,7 @@ export async function sendApiRequest( return { ok: false, message: 'Authentication Error', - cause: getErrorCause(error), + cause: errorMessage(error), } } if (!apiToken) { @@ -922,7 +922,7 @@ export async function sendApiRequest( debugDir('error', e) const cause = isErrnoException(e) && e.code === 'ETIMEDOUT' - ? `${getErrorCause(e)} (path: ${path})` + ? `${errorMessage(e)} (path: ${path})` : `Unexpected error parsing response JSON (path: ${path})` return { ok: false, diff --git a/src/utils/api.test.mts b/src/utils/api.test.mts index 1fc8d110b2..c4e7335bc1 100644 --- a/src/utils/api.test.mts +++ b/src/utils/api.test.mts @@ -117,7 +117,7 @@ vi.mock('./config.mts', () => ({ isConfigFromFlag: mockIsConfigFromFlag, })) vi.mock('./errors.mts', () => ({ - getErrorCause: (error: unknown) => + errorMessage: (error: unknown) => error instanceof Error ? error.message : 'Unknown error', })) diff --git a/src/utils/coana/release.mts b/src/utils/coana/release.mts index 34ff4c95ca..f04b8a95c8 100644 --- a/src/utils/coana/release.mts +++ b/src/utils/coana/release.mts @@ -31,7 +31,7 @@ import constants, { SOCKET_CLI_API_TOKEN_VARIABLES, } from '../../constants.mts' import { apiFetch, sendApiRequest } from '../api.mts' -import { getErrorCause } from '../errors.mts' +import { errorMessage } from '../errors.mts' import { withTmpDir } from '../fs.mts' import { getCliUserAgent, @@ -149,7 +149,7 @@ function coanaSpawnErrorResult(e: unknown): CResult { } const detailSuffix = details.length ? ` (${details.join(', ')})` : '' // Coana logs some failures, e.g. unresolved Gradle dependencies, to stdout. - const detail = stderr || stdout || getErrorCause(e) + const detail = stderr || stdout || errorMessage(e) const message = typeof exitCode === 'string' ? `Failed to launch Coana${detailSuffix}: ${detail}` @@ -276,7 +276,7 @@ async function getCoanaCliDir( return { ok: false, message: `Failed to get the Coana CLI ${versionSpec}`, - cause: getErrorCause(e), + cause: errorMessage(e), } } @@ -598,7 +598,7 @@ export async function spawnCoana( return { ok: false, message: 'Could not prepare the embedded Coana CLI', - cause: getErrorCause(error), + cause: errorMessage(error), } } } diff --git a/src/utils/config.mts b/src/utils/config.mts index 800c1ff5b7..bd4a8cd622 100644 --- a/src/utils/config.mts +++ b/src/utils/config.mts @@ -29,7 +29,7 @@ import config from '@socketsecurity/config' import { debugConfig, debugDir, debugFn } from './debug.mts' import { getEditableJsonClass } from './editable-json.mts' -import { getErrorCause } from './errors.mts' +import { errorMessage } from './errors.mts' import { safeReadFileSync } from './fs.mts' import { logger } from './logger.mts' import { naturalCompare } from './sorts.mts' @@ -190,7 +190,7 @@ export function findSocketYmlSync( return { ok: false, message: `Found file but was unable to parse ${ymlPath}`, - cause: getErrorCause(e), + cause: errorMessage(e), } } } diff --git a/src/utils/cve-to-ghsa.mts b/src/utils/cve-to-ghsa.mts index afdbbfea29..3f65a46b1c 100644 --- a/src/utils/cve-to-ghsa.mts +++ b/src/utils/cve-to-ghsa.mts @@ -1,4 +1,4 @@ -import { getErrorCause } from './errors.mts' +import { errorMessage } from './errors.mts' import { cacheFetch, getOctokit } from './github.mts' import type { CResult } from '../types.mts' @@ -42,7 +42,7 @@ export async function convertCveToGhsa( data: response.data[0]!.ghsa_id, } } catch (e) { - const errorCause = getErrorCause(e) + const errorCause = errorMessage(e) const errorLower = errorCause.toLowerCase() // Detect GitHub API rate limit and network errors. const isRateLimitOrNetworkError = diff --git a/src/utils/errors.mts b/src/utils/errors.mts index dc1c51c58b..9abefee8ea 100644 --- a/src/utils/errors.mts +++ b/src/utils/errors.mts @@ -9,7 +9,7 @@ * Key Functions: * - captureException: Send errors to Sentry for monitoring * - formatErrorWithDetail: Format errors with detailed context - * - getErrorCause: Get error cause with fallback to UNKNOWN_ERROR + * - errorMessage: Get an error message with fallback to UNKNOWN_ERROR * - getErrorMessage: Extract error message from any thrown value * * Error Handling Strategy: @@ -108,9 +108,9 @@ export function getErrorMessageOr(error: unknown, fallback: string): string { * @returns The error message or UNKNOWN_ERROR constant * * @example - * return { ok: false, message: 'Operation failed', cause: getErrorCause(e) } + * return { ok: false, message: 'Operation failed', cause: errorMessage(e) } */ -export function getErrorCause(error: unknown): string { +export function errorMessage(error: unknown): string { return getErrorMessageOr(error, UNKNOWN_ERROR) } @@ -132,6 +132,6 @@ export function formatErrorWithDetail( baseMessage: string, error: unknown, ): string { - const errorMessage = getErrorMessage(error) - return `${baseMessage}${errorMessage ? `: ${errorMessage}` : ''}` + const detail = getErrorMessage(error) + return `${baseMessage}${detail ? `: ${detail}` : ''}` } diff --git a/src/utils/errors.test.mts b/src/utils/errors.test.mts index 051dcb00a1..d25a06ad8c 100644 --- a/src/utils/errors.test.mts +++ b/src/utils/errors.test.mts @@ -7,8 +7,8 @@ import { describe, expect, it } from 'vitest' import { AuthError, InputError, + errorMessage, formatErrorWithDetail, - getErrorCause, getErrorMessage, getErrorMessageOr, isErrnoException, @@ -121,22 +121,22 @@ describe('getErrorMessageOr', () => { }) }) -describe('getErrorCause', () => { +describe('errorMessage', () => { it('should extract error message as cause', () => { const error = new Error('Something went wrong') - expect(getErrorCause(error)).toBe('Something went wrong') + expect(errorMessage(error)).toBe('Something went wrong') }) it('should return UNKNOWN_ERROR for non-error values', () => { - expect(getErrorCause(null)).toBe(UNKNOWN_ERROR) - expect(getErrorCause(undefined)).toBe(UNKNOWN_ERROR) - expect(getErrorCause('string')).toBe(UNKNOWN_ERROR) - expect(getErrorCause(123)).toBe(UNKNOWN_ERROR) + expect(errorMessage(null)).toBe(UNKNOWN_ERROR) + expect(errorMessage(undefined)).toBe(UNKNOWN_ERROR) + expect(errorMessage('string')).toBe(UNKNOWN_ERROR) + expect(errorMessage(123)).toBe(UNKNOWN_ERROR) }) it('should return UNKNOWN_ERROR for error with empty message', () => { const error = new Error('') - expect(getErrorCause(error)).toBe(UNKNOWN_ERROR) + expect(errorMessage(error)).toBe(UNKNOWN_ERROR) }) }) diff --git a/src/utils/purl-to-ghsa.mts b/src/utils/purl-to-ghsa.mts index 1f649cdced..ca4cafee7d 100644 --- a/src/utils/purl-to-ghsa.mts +++ b/src/utils/purl-to-ghsa.mts @@ -1,5 +1,5 @@ import { LATEST } from '../constants.mts' -import { getErrorCause } from './errors.mts' +import { errorMessage } from './errors.mts' import { cacheFetch, getOctokit } from './github.mts' import { getPurlObject } from './purl.mts' @@ -65,7 +65,7 @@ export async function convertPurlToGhsas( } catch (e) { return { ok: false, - message: `Failed to convert PURL to GHSA: ${getErrorCause(e)}`, + message: `Failed to convert PURL to GHSA: ${errorMessage(e)}`, } } } diff --git a/src/utils/sdk.mts b/src/utils/sdk.mts index dbe85a82da..8fed93926f 100644 --- a/src/utils/sdk.mts +++ b/src/utils/sdk.mts @@ -34,7 +34,7 @@ import { SocketSdk, createUserAgentFromPkgJson } from '@socketsecurity/sdk' import { getExtraCaCerts } from './api-transport.mts' import { getConfigValueOrUndef, isConfigFromFlag } from './config.mts' import { debugApiRequest, debugApiResponse } from './debug.mts' -import { getErrorCause } from './errors.mts' +import { errorMessage } from './errors.mts' import { logger } from './logger.mts' import { readOAuthCredentials, resolveOAuthAccessToken } from './oauth.mts' import { isNonEmptyString } from './strings.mts' @@ -275,7 +275,7 @@ export async function setupSdk( return { ok: false, message: 'Auth Error', - cause: getErrorCause(error), + cause: errorMessage(error), } } diff --git a/src/utils/sdk.test.mts b/src/utils/sdk.test.mts index 051b93aea3..9a025ca241 100644 --- a/src/utils/sdk.test.mts +++ b/src/utils/sdk.test.mts @@ -102,7 +102,7 @@ vi.mock('./config.mts', () => ({ })) vi.mock('./errors.mts', () => ({ - getErrorCause: (error: unknown) => + errorMessage: (error: unknown) => error instanceof Error ? error.message : 'Unknown error', }))