Skip to content

Commit 547c3e8

Browse files
committed
make all errors a function
1 parent d59de3e commit 547c3e8

File tree

9 files changed

+86
-53
lines changed

9 files changed

+86
-53
lines changed

adm-zip.js

Lines changed: 16 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ module.exports = function (/**String*/ input, /** object */ options) {
5959
opts.filename = input;
6060
inBuffer = filetools.fs.readFileSync(input);
6161
} else {
62-
throw new Error(Utils.Errors.INVALID_FILENAME);
62+
throw Utils.Errors.INVALID_FILENAME();
6363
}
6464
}
6565

@@ -316,7 +316,7 @@ module.exports = function (/**String*/ input, /** object */ options) {
316316
// add file into zip file
317317
this.addFile(zipPath, data, comment, _attr);
318318
} else {
319-
throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath));
319+
throw Utils.Errors.FILE_NOT_FOUND(localPath);
320320
}
321321
},
322322

@@ -398,7 +398,7 @@ module.exports = function (/**String*/ input, /** object */ options) {
398398
}
399399
}
400400
} else {
401-
throw new Error(Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath));
401+
throw Utils.Errors.FILE_NOT_FOUND(localPath);
402402
}
403403
},
404404

@@ -423,7 +423,7 @@ module.exports = function (/**String*/ input, /** object */ options) {
423423
var self = this;
424424
filetools.fs.open(localPath, "r", function (err) {
425425
if (err && err.code === "ENOENT") {
426-
callback(undefined, Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath));
426+
callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath));
427427
} else if (err) {
428428
callback(undefined, err);
429429
} else {
@@ -520,7 +520,7 @@ module.exports = function (/**String*/ input, /** object */ options) {
520520

521521
filetools.fs.open(localPath, "r", function (err) {
522522
if (err && err.code === "ENOENT") {
523-
callback(undefined, Utils.Errors.FILE_NOT_FOUND.replace("%s", localPath));
523+
callback(undefined, Utils.Errors.FILE_NOT_FOUND(localPath));
524524
} else if (err) {
525525
callback(undefined, err);
526526
} else {
@@ -675,7 +675,7 @@ module.exports = function (/**String*/ input, /** object */ options) {
675675

676676
var item = getEntry(entry);
677677
if (!item) {
678-
throw new Error(Utils.Errors.NO_ENTRY);
678+
throw Utils.Errors.NO_ENTRY();
679679
}
680680

681681
var entryName = canonical(item.entryName);
@@ -688,7 +688,7 @@ module.exports = function (/**String*/ input, /** object */ options) {
688688
if (child.isDirectory) return;
689689
var content = child.getData();
690690
if (!content) {
691-
throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
691+
throw Utils.Errors.CANT_EXTRACT_FILE();
692692
}
693693
var name = canonical(child.entryName);
694694
var childName = sanitize(targetPath, maintainEntryPath ? name : pth.basename(name));
@@ -700,10 +700,10 @@ module.exports = function (/**String*/ input, /** object */ options) {
700700
}
701701

702702
var content = item.getData(_zip.password);
703-
if (!content) throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
703+
if (!content) throw Utils.Errors.CANT_EXTRACT_FILE();
704704

705705
if (filetools.fs.existsSync(target) && !overwrite) {
706-
throw new Error(Utils.Errors.CANT_OVERRIDE);
706+
throw Utils.Errors.CANT_OVERRIDE();
707707
}
708708
// The reverse operation for attr depend on method addFile()
709709
const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
@@ -751,9 +751,8 @@ module.exports = function (/**String*/ input, /** object */ options) {
751751
keepOriginalPermission = get_Bool(false, keepOriginalPermission);
752752
pass = get_Str(keepOriginalPermission, pass);
753753
overwrite = get_Bool(false, overwrite);
754-
if (!_zip) {
755-
throw new Error(Utils.Errors.NO_ZIP);
756-
}
754+
if (!_zip) throw Utils.Errors.NO_ZIP();
755+
757756
_zip.entries.forEach(function (entry) {
758757
var entryName = sanitize(targetPath, canonical(entry.entryName));
759758
if (entry.isDirectory) {
@@ -762,15 +761,15 @@ module.exports = function (/**String*/ input, /** object */ options) {
762761
}
763762
var content = entry.getData(pass);
764763
if (!content) {
765-
throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
764+
throw Utils.Errors.CANT_EXTRACT_FILE();
766765
}
767766
// The reverse operation for attr depend on method addFile()
768767
const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;
769768
filetools.writeFileTo(entryName, content, overwrite, fileAttr);
770769
try {
771770
filetools.fs.utimesSync(entryName, entry.header.time, entry.header.time);
772771
} catch (err) {
773-
throw new Error(Utils.Errors.CANT_EXTRACT_FILE);
772+
throw Utils.Errors.CANT_EXTRACT_FILE();
774773
}
775774
});
776775
},
@@ -801,7 +800,7 @@ module.exports = function (/**String*/ input, /** object */ options) {
801800
});
802801
}
803802
if (!_zip) {
804-
callback(new Error(Utils.Errors.NO_ZIP));
803+
callback(Utils.Errors.NO_ZIP());
805804
return;
806805
}
807806

@@ -846,9 +845,9 @@ module.exports = function (/**String*/ input, /** object */ options) {
846845
const filePath = sanitize(targetPath, entryName);
847846
entry.getDataAsync(function (content, err_1) {
848847
if (err_1) {
849-
next(new Error(err_1));
848+
next(err_1);
850849
} else if (!content) {
851-
next(new Error(Utils.Errors.CANT_EXTRACT_FILE));
850+
next(Utils.Errors.CANT_EXTRACT_FILE());
852851
} else {
853852
// The reverse operation for attr depend on method addFile()
854853
const fileAttr = keepOriginalPermission ? entry.header.fileAttr : undefined;

headers/entryHeader.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ module.exports = function () {
212212
var data = input.slice(_offset, _offset + Constants.LOCHDR);
213213
// 30 bytes and should start with "PK\003\004"
214214
if (data.readUInt32LE(0) !== Constants.LOCSIG) {
215-
throw new Error(Utils.Errors.INVALID_LOC);
215+
throw Utils.Errors.INVALID_LOC();
216216
}
217217

218218
// version needed to extract
@@ -243,7 +243,7 @@ module.exports = function () {
243243
loadFromBinary: function (/*Buffer*/ data) {
244244
// data should be 46 bytes and start with "PK 01 02"
245245
if (data.length !== Constants.CENHDR || data.readUInt32LE(0) !== Constants.CENSIG) {
246-
throw new Error(Utils.Errors.INVALID_CEN);
246+
throw Utils.Errors.INVALID_CEN();
247247
}
248248
// version made by
249249
_verMade = data.readUInt16LE(Constants.CENVEM);

headers/mainHeader.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ module.exports = function () {
5656
(data.length !== Constants.ENDHDR || data.readUInt32LE(0) !== Constants.ENDSIG) &&
5757
(data.length < Constants.ZIP64HDR || data.readUInt32LE(0) !== Constants.ZIP64SIG)
5858
) {
59-
throw new Error(Utils.Errors.INVALID_END);
59+
throw Utils.Errors.INVALID_END();
6060
}
6161

6262
if (data.readUInt32LE(0) === Constants.ENDSIG) {

methods/zipcrypto.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// node crypt, we use it for generate salt
44
// eslint-disable-next-line node/no-unsupported-features/node-builtins
55
const { randomFillSync } = require("crypto");
6+
const Errors = require("../util/errors");
67

78
// generate CRC32 lookup table
89
const crctable = new Uint32Array(256).map((t, crc) => {
@@ -124,7 +125,7 @@ function decrypt(/*Buffer*/ data, /*Object*/ header, /*String, Buffer*/ pwd) {
124125

125126
//3. does password meet expectations
126127
if (salt[11] !== verifyByte) {
127-
throw "ADM-ZIP: Wrong Password";
128+
throw Errors.WRONG_PASSWORD();
128129
}
129130

130131
// 4. decode content

test/large_directory_size/large_directory_size.test.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
const assert = require("assert");
44
const path = require("path");
55
const Zip = require("../../adm-zip");
6+
const Errors = require("../../util/errors");
67

78
describe("read zip file header with invalid large number of entries", () => {
89
it("throws too large error", () => {
@@ -11,6 +12,6 @@ describe("read zip file header with invalid large number of entries", () => {
1112
// assert that the following call throws an exception
1213
assert.throws(() => {
1314
zip.getEntries();
14-
}, new Error("Number of disk entries is too large"));
15+
}, Errors.DISK_ENTRY_TOO_LARGE());
1516
});
1617
});

util/errors.js

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
1-
module.exports = {
1+
const errors = {
22
/* Header error messages */
33
INVALID_LOC: "Invalid LOC header (bad signature)",
44
INVALID_CEN: "Invalid CEN header (bad signature)",
55
INVALID_END: "Invalid END header (bad signature)",
66

7+
/* Descriptor */
8+
DESCRIPTOR_NOT_EXIST: "No descriptor present",
9+
DESCRIPTOR_UNKNOWN: "Unknown descriptor format",
10+
DESCRIPTOR_FAULTY: "Descriptor data is malformed",
11+
712
/* ZipEntry error messages*/
813
NO_DATA: "Nothing to decompress",
9-
BAD_CRC: "CRC32 checksum failed",
10-
FILE_IN_THE_WAY: "There is a file in the way: %s",
14+
BAD_CRC: "CRC32 checksum failed {0}",
15+
FILE_IN_THE_WAY: "There is a file in the way: {0}",
1116
UNKNOWN_METHOD: "Invalid/unsupported compression method",
1217

1318
/* Inflater error messages */
@@ -29,8 +34,30 @@ module.exports = {
2934
NO_ZIP: "No zip file was loaded",
3035
NO_ENTRY: "Entry doesn't exist",
3136
DIRECTORY_CONTENT_ERROR: "A directory cannot have content",
32-
FILE_NOT_FOUND: "File not found: %s",
37+
FILE_NOT_FOUND: 'File not found: "{0}"',
3338
NOT_IMPLEMENTED: "Not implemented",
3439
INVALID_FILENAME: "Invalid filename",
35-
INVALID_FORMAT: "Invalid or unsupported zip format. No END header found"
40+
INVALID_FORMAT: "Invalid or unsupported zip format. No END header found",
41+
INVALID_PASS_PARAM: "Incompatible password parameter",
42+
WRONG_PASSWORD: "Wrong Password",
43+
44+
/* ADM-ZIP */
45+
COMMENT_TOO_LONG: "Comment is too long", // Comment can be max 65535 bytes long (NOTE: some non-US characters may take more space)
46+
EXTRA_FIELD_PARSE_ERROR: "Extra field parsing error"
3647
};
48+
49+
// template
50+
function E(message) {
51+
return function (...args) {
52+
if (args.length) { // Allow {0} .. {9} arguments in error message, based on argument number
53+
message = message.replace(/\{(\d)\}/g, (_, n) => args[n] || '');
54+
}
55+
56+
return new Error('ADM-ZIP: ' + message);
57+
};
58+
}
59+
60+
// Init errors with template
61+
for (const msg of Object.keys(errors)) {
62+
exports[msg] = E(errors[msg]);
63+
}

util/utils.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ Utils.prototype.makeDir = function (/*String*/ folder) {
5151
} catch (e) {
5252
self.fs.mkdirSync(resolvedPath);
5353
}
54-
if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY.replace("%s", resolvedPath);
54+
if (stat && stat.isFile()) throw Errors.FILE_IN_THE_WAY(`"${resolvedPath}"`);
5555
});
5656
}
5757

zipEntry.js

Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ module.exports = function (/** object */ options, /*Buffer*/ input) {
3939
const dataEndOffset = _centralHeader.realDataOffset + _centralHeader.compressedSize;
4040
// no descriptor after compressed data, instead new local header
4141
if (input.readUInt32LE(dataEndOffset) == Constants.LOCSIG || input.readUInt32LE(dataEndOffset) == Constants.CENSIG) {
42-
throw new Error("ADM-ZIP: No descriptor present");
42+
throw Utils.Errors.DESCRIPTOR_NOT_EXIST();
4343
}
4444

4545
// get decriptor data
@@ -54,12 +54,12 @@ module.exports = function (/** object */ options, /*Buffer*/ input) {
5454
descriptor.compressedSize = input.readUInt32LE(dataEndOffset + Constants.EXTSIZ - 4);
5555
descriptor.size = input.readUInt32LE(dataEndOffset + Constants.EXTLEN - 4);
5656
} else {
57-
throw new Error("ADM-ZIP: Unknown descriptor format");
57+
throw Utils.Errors.DESCRIPTOR_UNKNOWN();
5858
}
5959

6060
// check data integrity
6161
if (descriptor.compressedSize !== _centralHeader.compressedSize || descriptor.size !== _centralHeader.size || descriptor.crc !== _centralHeader.crc) {
62-
throw new Error("ADM-ZIP: Descriptor data is malformed");
62+
throw Utils.Errors.DESCRIPTOR_FAULTY();
6363
}
6464
if (Utils.crc32(data) !== descriptor.crc) {
6565
return false;
@@ -80,7 +80,7 @@ module.exports = function (/** object */ options, /*Buffer*/ input) {
8080
}
8181
if (_isDirectory) {
8282
if (async && callback) {
83-
callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR); //si added error.
83+
callback(Buffer.alloc(0), Utils.Errors.DIRECTORY_CONTENT_ERROR()); //si added error.
8484
}
8585
return Buffer.alloc(0);
8686
}
@@ -95,7 +95,7 @@ module.exports = function (/** object */ options, /*Buffer*/ input) {
9595

9696
if (_centralHeader.encrypted) {
9797
if ("string" !== typeof pass && !Buffer.isBuffer(pass)) {
98-
throw new Error("ADM-ZIP: Incompatible password parameter");
98+
throw Utils.Errors.INVALID_PASS_PARAM();
9999
}
100100
compressedData = Methods.ZipCrypto.decrypt(compressedData, _centralHeader, pass);
101101
}
@@ -106,8 +106,8 @@ module.exports = function (/** object */ options, /*Buffer*/ input) {
106106
case Utils.Constants.STORED:
107107
compressedData.copy(data);
108108
if (!crc32OK(data)) {
109-
if (async && callback) callback(data, Utils.Errors.BAD_CRC); //si added error
110-
throw new Error(Utils.Errors.BAD_CRC);
109+
if (async && callback) callback(data, Utils.Errors.BAD_CRC()); //si added error
110+
throw Utils.Errors.BAD_CRC();
111111
} else {
112112
//si added otherwise did not seem to return data.
113113
if (async && callback) callback(data);
@@ -119,15 +119,15 @@ module.exports = function (/** object */ options, /*Buffer*/ input) {
119119
const result = inflater.inflate(data);
120120
result.copy(data, 0);
121121
if (!crc32OK(data)) {
122-
throw new Error(Utils.Errors.BAD_CRC + " " + _entryName.toString());
122+
throw Utils.Errors.BAD_CRC(`"${decoder.decode(_entryName)}"`);
123123
}
124124
return data;
125125
} else {
126126
inflater.inflateAsync(function (result) {
127127
result.copy(result, 0);
128128
if (callback) {
129129
if (!crc32OK(result)) {
130-
callback(result, Utils.Errors.BAD_CRC); //si added error
130+
callback(result, Utils.Errors.BAD_CRC()); //si added error
131131
} else {
132132
callback(result);
133133
}
@@ -136,8 +136,8 @@ module.exports = function (/** object */ options, /*Buffer*/ input) {
136136
}
137137
break;
138138
default:
139-
if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD);
140-
throw new Error(Utils.Errors.UNKNOWN_METHOD);
139+
if (async && callback) callback(Buffer.alloc(0), Utils.Errors.UNKNOWN_METHOD());
140+
throw Utils.Errors.UNKNOWN_METHOD();
141141
}
142142
}
143143

@@ -190,18 +190,22 @@ module.exports = function (/** object */ options, /*Buffer*/ input) {
190190
}
191191

192192
function parseExtra(data) {
193-
var offset = 0;
194-
var signature, size, part;
195-
while (offset < data.length) {
196-
signature = data.readUInt16LE(offset);
197-
offset += 2;
198-
size = data.readUInt16LE(offset);
199-
offset += 2;
200-
part = data.slice(offset, offset + size);
201-
offset += size;
202-
if (Constants.ID_ZIP64 === signature) {
203-
parseZip64ExtendedInformation(part);
193+
try {
194+
var offset = 0;
195+
var signature, size, part;
196+
while (offset < data.length) {
197+
signature = data.readUInt16LE(offset);
198+
offset += 2;
199+
size = data.readUInt16LE(offset);
200+
offset += 2;
201+
part = data.slice(offset, offset + size);
202+
offset += size;
203+
if (Constants.ID_ZIP64 === signature) {
204+
parseZip64ExtendedInformation(part);
205+
}
204206
}
207+
} catch (error) {
208+
throw Utils.Errors.EXTRA_FIELD_PARSE_ERROR();
205209
}
206210
}
207211

@@ -272,10 +276,11 @@ module.exports = function (/** object */ options, /*Buffer*/ input) {
272276
set comment(val) {
273277
_comment = Utils.toBuffer(val, decoder.encode);
274278
_centralHeader.commentLength = _comment.length;
279+
if (_comment.length > 0xffff) throw Utils.Errors.COMMENT_TOO_LONG();
275280
},
276281

277282
get name() {
278-
var n = _entryName.toString();
283+
var n = decoder.decode(_entryName);
279284
return _isDirectory
280285
? n
281286
.substr(n.length - 1)

zipFile.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) {
5656
loadedEntries = true;
5757
entryTable = {};
5858
if (mainHeader.diskEntries > (inBuffer.length - mainHeader.offset) / Utils.Constants.CENHDR) {
59-
throw new Error(Utils.Errors.DISK_ENTRY_TOO_LARGE);
59+
throw Utils.Errors.DISK_ENTRY_TOO_LARGE();
6060
}
6161
entryList = new Array(mainHeader.diskEntries); // total number of entries
6262
var index = mainHeader.offset; // offset of first CEN header
@@ -120,7 +120,7 @@ module.exports = function (/*Buffer|null*/ inBuffer, /** object */ options) {
120120
}
121121
}
122122

123-
if (endOffset == -1) throw new Error(Utils.Errors.INVALID_FORMAT);
123+
if (endOffset == -1) throw Utils.Errors.INVALID_FORMAT();
124124

125125
mainHeader.loadFromBinary(inBuffer.slice(endOffset, endStart));
126126
if (mainHeader.commentLength) {

0 commit comments

Comments
 (0)