Skip to content

Commit 7936ba5

Browse files
authored
chore: standardize errors (CN-944) (#786)
* chore: standardized errors * fix: re-added truthy check * fix: reworked type check
1 parent 9313782 commit 7936ba5

File tree

20 files changed

+165
-62
lines changed

20 files changed

+165
-62
lines changed

lib/analyzer/applications/node-modules-utils.ts

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as Debug from "debug";
22
import { mkdir, mkdtemp, rm, stat, writeFile } from "fs/promises";
33
import * as os from "os";
44
import * as path from "path";
5+
import { getErrorMessage } from "../../error-utils";
56
import { FilePathToContent, FilesByDirMap } from "./types";
67
const debug = Debug("snyk");
78

@@ -52,7 +53,9 @@ async function createSyntheticManifest(
5253
await writeFile(tempRootManifestPath, "{}", "utf-8");
5354
} catch (error) {
5455
debug(
55-
`Error while writing file ${tempRootManifestPath} : ${error.message}`,
56+
`Error while writing file ${tempRootManifestPath} : ${getErrorMessage(
57+
error,
58+
)}`,
5659
);
5760
}
5861
}
@@ -117,7 +120,9 @@ async function persistNodeModules(
117120
return result;
118121
} catch (error) {
119122
debug(
120-
`Failed to copy the application manifest files locally: ${error.message}`,
123+
`Failed to copy the application manifest files locally: ${getErrorMessage(
124+
error,
125+
)}`,
121126
);
122127
return {
123128
tempDir: tmpDir,
@@ -134,7 +139,7 @@ async function createFile(
134139
await mkdir(path.dirname(filePath), { recursive: true });
135140
await writeFile(filePath, fileContent, "utf-8");
136141
} catch (error) {
137-
debug(`Error while creating file ${filePath} : ${error.message}`);
142+
debug(`Error while creating file ${filePath} : ${getErrorMessage(error)}`);
138143
}
139144
}
140145

@@ -248,6 +253,6 @@ async function cleanupAppNodeModules(appRootDir: string): Promise<void> {
248253
try {
249254
await rm(appRootDir, { recursive: true });
250255
} catch (error) {
251-
debug(`Error while removing ${appRootDir} : ${error.message}`);
256+
debug(`Error while removing ${appRootDir} : ${getErrorMessage(error)}`);
252257
}
253258
}

lib/analyzer/applications/node.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import * as Debug from "debug";
33
import * as path from "path";
44
import * as lockFileParser from "snyk-nodejs-lockfile-parser";
55
import * as resolveDeps from "snyk-resolve-deps";
6+
import { getErrorMessage } from "../../error-utils";
67
import { DepGraphFact, TestedFilesFact } from "../../facts";
78

89
const debug = Debug("snyk");
@@ -162,7 +163,9 @@ async function depGraphFromNodeModules(
162163
});
163164
} catch (error) {
164165
debug(
165-
`An error occurred while analysing node_modules dir: ${error.message}`,
166+
`An error occurred while analysing node_modules dir: ${getErrorMessage(
167+
error,
168+
)}`,
166169
);
167170
} finally {
168171
await cleanupAppNodeModules(tempDir);
@@ -300,7 +303,9 @@ async function depGraphFromManifestFiles(
300303
);
301304
} catch (err) {
302305
debug(
303-
`An error occurred while analysing a pair of manifest and lock files: ${err.message}`,
306+
`An error occurred while analysing a pair of manifest and lock files: ${getErrorMessage(
307+
err,
308+
)}`,
304309
);
305310
continue;
306311
}

lib/analyzer/applications/python/pip.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import * as Debug from "debug";
33
import { eventLoopSpinner } from "event-loop-spinner";
44
import * as path from "path";
55
import * as semver from "semver";
6+
import { getErrorMessage } from "../../../error-utils";
67
import { DepGraphFact } from "../../../facts";
78
import { compareVersions } from "../../../python-parser/common";
89
import { getPackageInfo } from "../../../python-parser/metadata-parser";
@@ -133,7 +134,7 @@ export async function pipFilesToScannedProjects(
133134
}
134135
metadataItems[packageInfo.name.toLowerCase()].push(packageInfo);
135136
} catch (err) {
136-
debug(err.message);
137+
debug(getErrorMessage(err));
137138
}
138139
}
139140
}

lib/analyzer/image-inspector.ts

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import * as Debug from "debug";
22
import * as fs from "fs";
33
import * as path from "path";
4+
import { getErrorMessage } from "../error-utils";
45

56
import { Docker, DockerOptions } from "../docker";
67
import { ImageName } from "../extractor/image";
@@ -34,7 +35,11 @@ function cleanupCallback(imageFolderPath: string, imageName: string) {
3435
try {
3536
fs.rmdirSync(imageFolderPath);
3637
} catch (err) {
37-
debug(`Can't remove folder ${imageFolderPath}, got error ${err.message}`);
38+
debug(
39+
`Can't remove folder ${imageFolderPath}, got error ${getErrorMessage(
40+
err,
41+
)}`,
42+
);
3843
}
3944
};
4045
}
@@ -57,8 +62,19 @@ async function pullWithDockerBinary(
5762
await docker.save(targetImage, saveLocation);
5863
return true;
5964
} catch (err) {
60-
debug(`couldn't pull ${targetImage} using docker binary: ${err.message}`);
61-
const errorMessage = err.stderr || err.message || err.toString();
65+
debug(
66+
`couldn't pull ${targetImage} using docker binary: ${getErrorMessage(
67+
err,
68+
)}`,
69+
);
70+
const stderrValue =
71+
err !== null &&
72+
typeof err === "object" &&
73+
"stderr" in (err as object) &&
74+
(err as { stderr: unknown }).stderr;
75+
const errorMessage = stderrValue
76+
? String(stderrValue)
77+
: getErrorMessage(err);
6278
handleDockerPullError(errorMessage, platform);
6379

6480
return false;
@@ -125,7 +141,7 @@ async function pullFromContainerRegistry(
125141
platform,
126142
);
127143
} catch (err) {
128-
handleDockerPullError(err.message);
144+
handleDockerPullError(getErrorMessage(err));
129145
throw err;
130146
}
131147
}
@@ -212,7 +228,7 @@ async function getImageArchive(
212228
} catch (error) {
213229
debug(
214230
`${targetImage} does not exist locally, proceeding to pull image.`,
215-
error.stack || error,
231+
getErrorMessage(error),
216232
);
217233
}
218234

@@ -369,7 +385,7 @@ function isLocalImageSameArchitecture(
369385
// Note: this is using the same flag/input pattern as the new Docker buildx: eg. linux/arm64/v8
370386
platformArchitecture = platformOption.split("/")[1];
371387
} catch (error) {
372-
debug(`Error parsing platform flag: '${error.message}'`);
388+
debug(`Error parsing platform flag: '${getErrorMessage(error)}'`);
373389
return false;
374390
}
375391

lib/analyzer/os-release/static.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as Debug from "debug";
22
import { normalize as normalizePath } from "path";
3+
import { getErrorMessage } from "../../error-utils";
34

45
import { DockerFileAnalysis } from "../../dockerfile/types";
56
import { ExtractedLayers } from "../../extractor/types";
@@ -74,7 +75,7 @@ export async function detect(
7475
try {
7576
osRelease = await handler(osReleaseFile);
7677
} catch (err) {
77-
debug(`Malformed OS release file: ${err.message}`);
78+
debug(`Malformed OS release file: ${getErrorMessage(err)}`);
7879
}
7980
if (osRelease) {
8081
break;

lib/analyzer/static-analyzer.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as Debug from "debug";
22
import { DockerFileAnalysis } from "../dockerfile";
3+
import { getErrorMessage } from "../error-utils";
34
import * as archiveExtractor from "../extractor";
45
import {
56
getGoModulesContentAction,
@@ -203,7 +204,7 @@ export async function analyze(
203204
dockerfileAnalysis,
204205
);
205206
} catch (err) {
206-
debug(`Could not detect OS release: ${err.message}`);
207+
debug(`Could not detect OS release: ${getErrorMessage(err)}`);
207208
throw new Error("Failed to detect OS release");
208209
}
209210

@@ -231,7 +232,7 @@ export async function analyze(
231232
chiselAnalyze(targetImage, chiselPackages),
232233
]);
233234
} catch (err) {
234-
debug(`Could not detect installed OS packages: ${err.message}`);
235+
debug(`Could not detect installed OS packages: ${getErrorMessage(err)}`);
235236
throw new Error("Failed to detect installed OS packages");
236237
}
237238

lib/compression-utils.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { Decompress as ZstdDecompress } from "fzstd";
2+
import { getErrorMessage } from "./error-utils";
23

34
/**
45
* Decompresses zstd-compressed data from a buffer.
@@ -22,10 +23,6 @@ export function decompressZstd(compressed: Buffer): Buffer {
2223

2324
return Buffer.concat(chunks);
2425
} catch (error) {
25-
throw new Error(
26-
`Zstd decompression failed: ${
27-
error instanceof Error ? error.message : String(error)
28-
}`,
29-
);
26+
throw new Error(`Zstd decompression failed: ${getErrorMessage(error)}`);
3027
}
3128
}

lib/error-utils.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
export function getErrorMessage(error: unknown): string {
2+
if (error instanceof Error) {
3+
return error.message;
4+
}
5+
return String(error);
6+
}

lib/extractor/decompress-maybe.ts

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { Decompress as ZstdDecompress } from "fzstd";
22
import { Transform } from "stream";
33
import { createGunzip } from "zlib";
4+
import { getErrorMessage } from "../error-utils";
45

56
/**
67
* Creates a transform stream that automatically detects and decompresses data based on magic numbers.
@@ -73,11 +74,7 @@ export function decompressMaybe(): Transform {
7374
zstdStream.push(new Uint8Array(combined), false);
7475
} catch (err) {
7576
callback(
76-
new Error(
77-
`zstd decompression failed: ${
78-
err instanceof Error ? err.message : String(err)
79-
}`,
80-
),
77+
new Error(`zstd decompression failed: ${getErrorMessage(err)}`),
8178
);
8279
return;
8380
}
@@ -108,11 +105,7 @@ export function decompressMaybe(): Transform {
108105
callback();
109106
} catch (err) {
110107
callback(
111-
new Error(
112-
`zstd decompression failed: ${
113-
err instanceof Error ? err.message : String(err)
114-
}`,
115-
),
108+
new Error(`zstd decompression failed: ${getErrorMessage(err)}`),
116109
);
117110
}
118111
} else {
@@ -133,11 +126,7 @@ export function decompressMaybe(): Transform {
133126
callback();
134127
} catch (err) {
135128
callback(
136-
new Error(
137-
`zstd decompression failed: ${
138-
err instanceof Error ? err.message : String(err)
139-
}`,
140-
),
129+
new Error(`zstd decompression failed: ${getErrorMessage(err)}`),
141130
);
142131
}
143132
} else if (!headerRead && buffer.length > 0) {

lib/extractor/docker-archive/layer.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { basename, normalize as normalizePath } from "path";
55
import { Readable } from "stream";
66
import { extract, Extract } from "tar-stream";
77
import { InvalidArchiveError } from "..";
8+
import { getErrorMessage } from "../../error-utils";
89
import { streamToJson } from "../../stream-utils";
910
import { PluginOptions } from "../../types";
1011
import { extractImageLayer } from "../layer";
@@ -46,7 +47,11 @@ export async function extractArchive(
4647
extractActions,
4748
);
4849
} catch (error) {
49-
debug(`Error extracting layer content from: '${error.message}'`);
50+
debug(
51+
`Error extracting layer content from: '${getErrorMessage(
52+
error,
53+
)}'`,
54+
);
5055
reject(new Error("Error reading tar archive"));
5156
}
5257
} else if (isManifestFile(normalizedName)) {
@@ -70,7 +75,9 @@ export async function extractArchive(
7075
);
7176
} catch (error) {
7277
debug(
73-
`Error getting layers and manifest content from docker archive: ${error.message}`,
78+
`Error getting layers and manifest content from docker archive: ${getErrorMessage(
79+
error,
80+
)}`,
7481
);
7582
reject(new InvalidArchiveError("Invalid Docker archive"));
7683
}

0 commit comments

Comments
 (0)