Skip to content

Commit

Permalink
refactor: Errors do not need new (#10030)
Browse files Browse the repository at this point in the history
Closes: #XXXX
Refs: endojs/endo#2445

## Description

Errors do not need `new`

For all construction calls to a `*Error` constructor, the `new` is not needed. IOW, just calling the `*Error` constructor as a function has the same effect.

### Security Considerations

none
### Scaling Considerations

none
### Documentation Considerations

none
### Testing Considerations

none
### Compatibility Considerations

none
### Upgrade Considerations

none
  • Loading branch information
erights authored Sep 5, 2024
1 parent c27a7e6 commit 80f5cb1
Show file tree
Hide file tree
Showing 28 changed files with 61 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export const getCurrent = async (addr, { readLatestHead }) => {
await readLatestHead(`published.wallet.${addr}.current`)
);
if (current === undefined) {
throw new Error(`undefined current node for ${addr}`);
throw Error(`undefined current node for ${addr}`);
}

// Repair a type misunderstanding seen in the wild.
Expand Down
2 changes: 1 addition & 1 deletion a3p-integration/proposals/c:stake-bld/test-lib/wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ export const getCurrent = async (addr, { readLatestHead }) => {
await readLatestHead(`published.wallet.${addr}.current`)
);
if (current === undefined) {
throw new Error(`undefined current node for ${addr}`);
throw Error(`undefined current node for ${addr}`);
}

// Repair a type misunderstanding seen in the wild.
Expand Down
4 changes: 2 additions & 2 deletions multichain-testing/test/ica-channel-close.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ const intentionalCloseAccountScenario = test.macro({
);
const newChannel = findNewChannel(channels, { rPortID, lPortID });
t.log('New Channel after Reactivate', newChannel);
if (!newChannel) throw new Error('Channel not found');
if (!newChannel) throw Error('Channel not found');
const newAddress = JSON.parse(newChannel.version).address;
t.is(newAddress, address, `same chain address is returned - ${chainName}`);
t.is(
Expand Down Expand Up @@ -314,7 +314,7 @@ const channelCloseInitScenario = test.macro({
).channels.find(
x => x.port_id === 'transfer' && x.connection_hops[0] === rConnectionID,
);
if (!transferChannel) throw new Error('Transfer channel not found.');
if (!transferChannel) throw Error('Transfer channel not found.');

const dstTransferChannel = {
chainId: chainInfo['agoric'].chainId,
Expand Down
4 changes: 2 additions & 2 deletions multichain-testing/tools/address.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const parseRemoteAddress = (
} => {
const match = address.match(REMOTE_ADDR_RE);
if (!match || !match.groups) {
throw new Error('Invalid remote address format');
throw Error('Invalid remote address format');
}

const { portID, version, channelID } = match.groups;
Expand All @@ -42,7 +42,7 @@ export const parseLocalAddress = (
} => {
const match = address.match(LOCAL_ADDR_RE);
if (!match || !match.groups) {
throw new Error('Invalid local address format');
throw Error('Invalid local address format');
}

const { portID, version, channelID } = match.groups;
Expand Down
2 changes: 1 addition & 1 deletion multichain-testing/tools/deploy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const makeDeployBuilder = (
const { stdout } = await execa`agoric run ${builder}`;
const match = stdout.match(/ (?<name>[-\w]+)-permit.json/);
if (!(match && match.groups)) {
throw new Error('no permit found');
throw Error('no permit found');
}
const plan = await readJSON(`./${match.groups.name}-plan.json`);
console.log(plan);
Expand Down
2 changes: 1 addition & 1 deletion multichain-testing/tools/makeHttpClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const jsonType = { 'Content-Type': 'application/json' };

const filterBadStatus = res => {
if (res.status >= 400) {
throw new Error(`Bad status on response: ${res.status}`);
throw Error(`Bad status on response: ${res.status}`);
}
return res;
};
Expand Down
2 changes: 1 addition & 1 deletion multichain-testing/tools/marshalTables.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ const synthesizeRemotable = (slot, iface) => {
*/
export const makeClientMarshaller = valToSlot => {
const noNewSlots = val => {
throw new Error(`unknown value: ${val}`);
throw Error(`unknown value: ${val}`);
};
const { convertValToSlot, convertSlotToVal } = makeTranslationTable(
valToSlot || noNewSlots,
Expand Down
2 changes: 1 addition & 1 deletion multichain-testing/tools/sleep.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ const retryUntilCondition = async <T>(
await sleep(retryIntervalMs, { log, setTimeout });
}

throw new Error(`${message} condition failed after ${maxRetries} retries.`);
throw Error(`${message} condition failed after ${maxRetries} retries.`);
};

export const makeRetryUntilCondition = (defaultOptions: RetryOptions = {}) => {
Expand Down
2 changes: 1 addition & 1 deletion packages/SwingSet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ If wavy dot syntax is used on a Promise which rejects, the method is not invoked
the return promise's `rejection` function is called instead:

```js
const badP = Promise.reject(new Error());
const badP = Promise.reject(Error());
const p2 = badP~.foo();
p2.then(undefined, rej => console.log('rejected', rej));
// prints 'rejected'
Expand Down
2 changes: 2 additions & 0 deletions packages/agoric-cli/src/commands/auction.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,8 @@ export const makeAuctionCommand = (
};

if (Object.keys(params).length === 0) {
// InvalidArgumentError is a class constructor, and so
// must be invoked with `new`.
throw new InvalidArgumentError(`no parameters given`);
}

Expand Down
6 changes: 6 additions & 0 deletions packages/agoric-cli/src/commands/gov.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ export const makeGovCommand = (_logger, io = {}) => {
const done = found.filter(it => it.instanceName === instanceName);
if (done.length > 0) {
console.warn(`invitation to ${instanceName} already accepted`, done);
// CommanderError is a class constructor, and so
// must be invoked with `new`.
throw new CommanderError(1, 'EALREADY', `already accepted`);
}
};
Expand Down Expand Up @@ -330,6 +332,8 @@ export const makeGovCommand = (_logger, io = {}) => {
const info = await readLatestHead(
`published.committees.${opts.pathname}.latestQuestion`,
).catch(err => {
// CommanderError is a class constructor, and so
// must be invoked with `new`.
throw new CommanderError(1, 'VSTORAGE_FAILURE', err.message);
});

Expand All @@ -346,6 +350,8 @@ export const makeGovCommand = (_logger, io = {}) => {
const votingRight = cont.find(it => it.instanceName === opts.instance);
if (!votingRight) {
console.debug('continuing ids', cont, 'for', current);
// CommanderError is a class constructor, and so
// must be invoked with `new`.
throw new CommanderError(
1,
'NO_INVITATION',
Expand Down
8 changes: 8 additions & 0 deletions packages/agoric-cli/src/commands/inter.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,8 @@ export const makeInterCommand = (
try {
return rawExec(file, args, ...opts);
} catch (err) {
// InvalidArgumentError is a class constructor, and so
// must be invoked with `new`.
throw new InvalidArgumentError(
`${err.message}: is ${file} in your $PATH?`,
);
Expand All @@ -239,6 +241,8 @@ export const makeInterCommand = (
const networkConfig = await getNetworkConfig(env);
return makeWalletUtils({ fetch, execFileSync, delay }, networkConfig);
} catch (err) {
// CommanderError is a class constructor, and so
// must be invoked with `new`.
throw new CommanderError(1, 'RPC_FAIL', err.message);
}
};
Expand Down Expand Up @@ -431,6 +435,8 @@ inter auction status
const parsePercent = v => {
const p = Number(v);
if (!(p >= -100 && p <= 100)) {
// InvalidArgumentError is a class constructor, and so
// must be invoked with `new`.
throw new InvalidArgumentError('must be between -100 and 100');
}
return p / 100;
Expand Down Expand Up @@ -498,6 +504,8 @@ inter auction status
const current = await getCurrent(from, { readLatestHead });
const liveIds = current.liveOffers.map(([i, _s]) => i);
if (!liveIds.includes(id)) {
// InvalidArgumentError is a class constructor, and so
// must be invoked with `new`.
throw new InvalidArgumentError(
`${id} not in live offer ids: ${liveIds}`,
);
Expand Down
2 changes: 2 additions & 0 deletions packages/agoric-cli/src/commands/test-upgrade.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ export const makeTestCommand = (
const networkConfig = await getNetworkConfig(env);
return makeWalletUtils({ fetch, execFileSync, delay }, networkConfig);
} catch (err) {
// CommanderError is a class constructor, and so
// must be invoked with `new`.
throw new CommanderError(1, 'RPC_FAIL', err.message);
}
};
Expand Down
2 changes: 1 addition & 1 deletion packages/agoric-cli/src/lib/bundles.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const PACKAGE_NAME_RE = /^(?:@[^/]+\/)?[^/]+/;
/** @param {Bundle} bundleObj*/
export const extractBundleInfo = async bundleObj => {
if (bundleObj.moduleFormat !== 'endoZipBase64') {
throw new Error('only endoZipBase64 is supported');
throw Error('only endoZipBase64 is supported');
}

const contents = Buffer.from(bundleObj.endoZipBase64, 'base64');
Expand Down
2 changes: 1 addition & 1 deletion packages/agoric-cli/src/lib/wallet.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export const getCurrent = async (addr, { readLatestHead }) => {
await readLatestHead(`published.wallet.${addr}.current`)
);
if (current === undefined) {
throw new Error(`undefined current node for ${addr}`);
throw Error(`undefined current node for ${addr}`);
}

// Repair a type misunderstanding seen in the wild.
Expand Down
2 changes: 2 additions & 0 deletions packages/agoric-cli/test/inter-cli.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,8 @@ const usageTest = (words, blurb = 'Command usage:') => {
program.addCommand(cmd);
for (const c of subCommands(program)) {
c.exitOverride(() => {
// CommanderError is a class constructor, and so
// must be invoked with `new`.
throw new CommanderError(1, 'usage', '');
});
}
Expand Down
2 changes: 1 addition & 1 deletion packages/casting/src/makeHttpClient.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ const { freeze } = Object;

const filterBadStatus = res => {
if (res.status >= 400) {
throw new Error(`Bad status on response: ${res.status}`);
throw Error(`Bad status on response: ${res.status}`);
}
return res;
};
Expand Down
12 changes: 6 additions & 6 deletions packages/cosmic-proto/src/codegen/binary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ export class BinaryReader implements IBinaryReader {
len: number;

assertBounds(): void {
if (this.pos > this.len) throw new RangeError('premature EOF');
if (this.pos > this.len) throw RangeError('premature EOF');
}

constructor(buf?: ArrayLike<number>) {
Expand All @@ -115,7 +115,7 @@ export class BinaryReader implements IBinaryReader {
fieldNo = tag >>> 3,
wireType = tag & 7;
if (fieldNo <= 0 || wireType < 0 || wireType > 5)
throw new Error(
throw Error(
'illegal tag: field no ' + fieldNo + ' wire type ' + wireType,
);
return [fieldNo, wireType, tag];
Expand Down Expand Up @@ -214,11 +214,11 @@ export class BinaryReader implements IBinaryReader {
}

float(): number {
throw new Error('float not supported');
throw Error('float not supported');
}

double(): number {
throw new Error('double not supported');
throw Error('double not supported');
}

bool(): boolean {
Expand Down Expand Up @@ -466,11 +466,11 @@ export class BinaryWriter implements IBinaryWriter {
sfixed32 = BinaryWriter.prototype.fixed32;

float(value: number): BinaryWriter {
throw new Error('float not supported' + value);
throw Error('float not supported' + value);
}

double(value: number): BinaryWriter {
throw new Error('double not supported' + value);
throw Error('double not supported' + value);
}

bytes(value: Uint8Array): BinaryWriter {
Expand Down
22 changes: 9 additions & 13 deletions packages/cosmic-proto/src/codegen/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export function omitDefault<T extends string | number | bigint | boolean>(
return input === BigInt(0) ? undefined : input;
}

throw new Error(`Got unsupported type ${typeof input}`);
throw Error(`Got unsupported type ${typeof input}`);
}

interface Duration {
Expand Down Expand Up @@ -241,9 +241,7 @@ export class Decimal {
const badCharacter = input.match(/[^0-9.]/);
if (badCharacter) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
throw new Error(
`Invalid character at position ${badCharacter.index! + 1}`,
);
throw Error(`Invalid character at position ${badCharacter.index! + 1}`);
}

let whole: string;
Expand All @@ -261,21 +259,21 @@ export class Decimal {
switch (parts.length) {
case 0:
case 1:
throw new Error(
throw Error(
'Fewer than two elements in split result. This must not happen here.',
);
case 2:
if (!parts[1]) throw new Error('Fractional part missing');
if (!parts[1]) throw Error('Fractional part missing');
whole = parts[0];
fractional = parts[1].replace(/0+$/, '');
break;
default:
throw new Error('More than one separator found');
throw Error('More than one separator found');
}
}

if (fractional.length > fractionalDigits) {
throw new Error('Got more fractional digits than supported');
throw Error('Got more fractional digits than supported');
}

const quantity = `${whole}${fractional.padEnd(fractionalDigits, '0')}`;
Expand All @@ -293,13 +291,11 @@ export class Decimal {

private static verifyFractionalDigits(fractionalDigits: number): void {
if (!Number.isInteger(fractionalDigits))
throw new Error('Fractional digits is not an integer');
throw Error('Fractional digits is not an integer');
if (fractionalDigits < 0)
throw new Error('Fractional digits must not be negative');
throw Error('Fractional digits must not be negative');
if (fractionalDigits > maxFractionalDigits) {
throw new Error(
`Fractional digits must not exceed ${maxFractionalDigits}`,
);
throw Error(`Fractional digits must not exceed ${maxFractionalDigits}`);
}
}
}
4 changes: 2 additions & 2 deletions packages/cosmic-proto/src/codegen/varint.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ export function varint64read(this: ReaderLike): [number, number] {
}
}

throw new Error('invalid varint');
throw Error('invalid varint');
}

/**
Expand Down Expand Up @@ -353,7 +353,7 @@ export function varint32read(this: ReaderLike): number {
for (let readBytes = 5; (b & 0x80) !== 0 && readBytes < 10; readBytes++)
b = this.buf[this.pos++];

if ((b & 0x80) != 0) throw new Error('invalid varint');
if ((b & 0x80) != 0) throw Error('invalid varint');

this.assertBounds();

Expand Down
4 changes: 1 addition & 3 deletions packages/cosmic-proto/src/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,7 @@ const QUERY_REQ_TYPEURL_RE =
export const typeUrlToGrpcPath = (typeUrl: Any['typeUrl']) => {
const match = typeUrl.match(QUERY_REQ_TYPEURL_RE);
if (!(match && match.groups)) {
throw new TypeError(
`Invalid typeUrl: ${typeUrl}. Must be a Query Request.`,
);
throw TypeError(`Invalid typeUrl: ${typeUrl}. Must be a Query Request.`);
}
const { serviceName, methodName } = match.groups;
return `/${serviceName}.Query/${methodName}`;
Expand Down
2 changes: 1 addition & 1 deletion packages/network/src/network.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ function throwIfInvalidPortName(specifiedName) {
// Valid symbols: ., ,, _, +, -, #, [, ], <, >
const portNameRegex = new RegExp('^[a-zA-Z0-9.,_+\\-#<>\\[\\]]{2,128}$');
if (!portNameRegex.test(specifiedName)) {
throw new Error(`Invalid IBC port name: ${specifiedName}`);
throw Error(`Invalid IBC port name: ${specifiedName}`);
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/notifier/src/publish-kit.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const makeQuietRejection = reason => {
return rejection;
};
const tooFarRejection = makeQuietRejection(
harden(new Error('Cannot read past end of iteration.')),
harden(Error('Cannot read past end of iteration.')),
);

export const PublisherI = M.interface('Publisher', {
Expand Down
2 changes: 1 addition & 1 deletion packages/smart-wallet/test/invitation1.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ test.serial('handle failure to create invitation', async t => {
return slowWithdrawPurse;
},
getAssetSubscription: () => {
throw new Error('TODO');
throw Error('TODO');
},
});

Expand Down
4 changes: 2 additions & 2 deletions packages/vats/src/proposals/localchain-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const testLocalChain = async (
let node = await chainStorage;
if (!node) {
console.error('testLocalChain no chainStorage');
throw new Error('no chainStorage');
throw Error('no chainStorage');
}

let result;
Expand Down Expand Up @@ -58,7 +58,7 @@ export const testLocalChain = async (
const emptyQuery = await E(localchain).queryMany([]);
console.info('emptyQuery', emptyQuery);
if (emptyQuery.length !== 0) {
throw new Error('emptyQuery results should be empty');
throw Error('emptyQuery results should be empty');
}

result = { success: true };
Expand Down
Loading

0 comments on commit 80f5cb1

Please sign in to comment.