Use Custom Error Classes for Validation

This commit is contained in:
2026-07-23 07:56:50 +00:00
parent 7cb9a29e77
commit 205fb18785
3 changed files with 112 additions and 40 deletions
+22 -4
View File
@@ -498,7 +498,7 @@ const testExponentialBackoffValidateOptionsRejectsNegativeValues = (): void => {
ExponentialBackoff.validateOptions({
...validExponentialBackoffOptions,
[field]: value,
})).toThrow(`${field} must be not less than 0`);
})).toThrow(`Exponential backoff option "${field}" is too small. Must be at least 0`);
}
};
@@ -515,7 +515,7 @@ const testExponentialBackoffValidateOptionsRejectsInvalidJitter = (): void => {
ExponentialBackoff.validateOptions({
...validExponentialBackoffOptions,
jitter: value,
})).toThrow('jitter must be not less than 0 or greater than 1');
})).toThrow('Exponential backoff option "jitter" is out of bounds. Must be between 0 and 1');
}
};
@@ -538,7 +538,24 @@ const testExponentialBackoffValidateOptionsRejectsNonFiniteValues = (): void =>
ExponentialBackoff.validateOptions({
...validExponentialBackoffOptions,
[field]: value,
})).toThrow(`${field} must be a finite number`);
})).toThrow(`Exponential backoff option "${field}" is invalid. Must be a finite number`);
}
};
/**
* Tests that {@link ExponentialBackoff.validateOptions} rejects non-integer values.
*/
const testExponentialBackoffValidateOptionsRejectsNonIntegerValues = (): void => {
// Define our test cases with each value being a non-integer
const nonIntegerCases = [{ field: 'maxAttempts', value: 1.5 }] as const;
// Iterate through the test cases and expect an error to be thrown
for (const { field, value } of nonIntegerCases) {
expect(() =>
ExponentialBackoff.validateOptions({
...validExponentialBackoffOptions,
[field]: value,
})).toThrow(`Exponential backoff option "${field}" is invalid. Must be an integer`);
}
};
@@ -561,7 +578,7 @@ const testExponentialBackoffValidateOptionsRejectsNaN = (): void => {
ExponentialBackoff.validateOptions({
...validExponentialBackoffOptions,
[field]: value,
})).toThrow(`${field} must be a finite number`);
})).toThrow(`Exponential backoff option "${field}" is invalid. Must be a finite number`);
}
};
@@ -589,6 +606,7 @@ const runTests = async (): Promise<void> => {
test('ExponentialBackoff.validateOptions: rejects negative values', testExponentialBackoffValidateOptionsRejectsNegativeValues);
test('ExponentialBackoff.validateOptions: rejects invalid jitter', testExponentialBackoffValidateOptionsRejectsInvalidJitter);
test('ExponentialBackoff.validateOptions: rejects Infinity', testExponentialBackoffValidateOptionsRejectsNonFiniteValues);
test('ExponentialBackoff.validateOptions: rejects non-integer values', testExponentialBackoffValidateOptionsRejectsNonIntegerValues);
test('ExponentialBackoff.validateOptions: rejects NaN', testExponentialBackoffValidateOptionsRejectsNaN);
};