refactor: use throw instead of Promise.reject (#10712)

Co-authored-by: Jiralite <33201955+Jiralite@users.noreply.github.com>
Co-authored-by: Renegade334 <Renegade334@users.noreply.github.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
Almeida
2025-01-24 09:39:05 +00:00
committed by Jiralite
parent 44a1e85847
commit 2663d76709
15 changed files with 61 additions and 64 deletions

View File

@@ -83,7 +83,7 @@
"no-void": "error", "no-void": "error",
"no-warning-comments": "warn", "no-warning-comments": "warn",
"prefer-promise-reject-errors": "error", "prefer-promise-reject-errors": "error",
"require-await": "warn", "require-await": "off",
"wrap-iife": "error", "wrap-iife": "error",
"yoda": "error", "yoda": "error",

View File

@@ -97,14 +97,14 @@ class GuildBanManager extends CachedManager {
* .then(console.log) * .then(console.log)
* .catch(console.error); * .catch(console.error);
*/ */
fetch(options) { async fetch(options) {
if (!options) return this._fetchMany(); if (!options) return this._fetchMany();
const { user, cache, force, limit, before, after } = options; const { user, cache, force, limit, before, after } = options;
const resolvedUser = this.client.users.resolveId(user ?? options); const resolvedUser = this.client.users.resolveId(user ?? options);
if (resolvedUser) return this._fetchSingle({ user: resolvedUser, cache, force }); if (resolvedUser) return this._fetchSingle({ user: resolvedUser, cache, force });
if (!before && !after && !limit && cache === undefined) { if (!before && !after && !limit && cache === undefined) {
return Promise.reject(new DiscordjsError(ErrorCodes.FetchBanResolveId)); throw new DiscordjsError(ErrorCodes.FetchBanResolveId);
} }
return this._fetchMany(options); return this._fetchMany(options);

View File

@@ -39,14 +39,14 @@ class GuildEmojiRoleManager extends DataManager {
* @param {RoleResolvable|RoleResolvable[]|Collection<Snowflake, Role>} roleOrRoles The role or roles to add * @param {RoleResolvable|RoleResolvable[]|Collection<Snowflake, Role>} roleOrRoles The role or roles to add
* @returns {Promise<GuildEmoji>} * @returns {Promise<GuildEmoji>}
*/ */
add(roleOrRoles) { async add(roleOrRoles) {
if (!Array.isArray(roleOrRoles) && !(roleOrRoles instanceof Collection)) roleOrRoles = [roleOrRoles]; if (!Array.isArray(roleOrRoles) && !(roleOrRoles instanceof Collection)) roleOrRoles = [roleOrRoles];
const resolvedRoles = []; const resolvedRoles = [];
for (const role of roleOrRoles.values()) { for (const role of roleOrRoles.values()) {
const resolvedRole = this.guild.roles.resolveId(role); const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) { if (!resolvedRole) {
return Promise.reject(new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role)); throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role);
} }
resolvedRoles.push(resolvedRole); resolvedRoles.push(resolvedRole);
} }
@@ -60,14 +60,14 @@ class GuildEmojiRoleManager extends DataManager {
* @param {RoleResolvable|RoleResolvable[]|Collection<Snowflake, Role>} roleOrRoles The role or roles to remove * @param {RoleResolvable|RoleResolvable[]|Collection<Snowflake, Role>} roleOrRoles The role or roles to remove
* @returns {Promise<GuildEmoji>} * @returns {Promise<GuildEmoji>}
*/ */
remove(roleOrRoles) { async remove(roleOrRoles) {
if (!Array.isArray(roleOrRoles) && !(roleOrRoles instanceof Collection)) roleOrRoles = [roleOrRoles]; if (!Array.isArray(roleOrRoles) && !(roleOrRoles instanceof Collection)) roleOrRoles = [roleOrRoles];
const resolvedRoleIds = []; const resolvedRoleIds = [];
for (const role of roleOrRoles.values()) { for (const role of roleOrRoles.values()) {
const roleId = this.guild.roles.resolveId(role); const roleId = this.guild.roles.resolveId(role);
if (!roleId) { if (!roleId) {
return Promise.reject(new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role)); throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role);
} }
resolvedRoleIds.push(roleId); resolvedRoleIds.push(roleId);
} }

View File

@@ -121,22 +121,22 @@ class GuildInviteManager extends CachedManager {
* .then(console.log) * .then(console.log)
* .catch(console.error); * .catch(console.error);
*/ */
fetch(options) { async fetch(options) {
if (!options) return this._fetchMany(); if (!options) return this._fetchMany();
if (typeof options === 'string') { if (typeof options === 'string') {
const code = resolveInviteCode(options); const code = resolveInviteCode(options);
if (!code) return Promise.reject(new DiscordjsError(ErrorCodes.InviteResolveCode)); if (!code) throw new DiscordjsError(ErrorCodes.InviteResolveCode);
return this._fetchSingle({ code, cache: true }); return this._fetchSingle({ code, cache: true });
} }
if (!options.code) { if (!options.code) {
if (options.channelId) { if (options.channelId) {
const id = this.guild.channels.resolveId(options.channelId); const id = this.guild.channels.resolveId(options.channelId);
if (!id) return Promise.reject(new DiscordjsError(ErrorCodes.GuildChannelResolve)); if (!id) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
return this._fetchChannelMany(id, options.cache); return this._fetchChannelMany(id, options.cache);
} }
if ('cache' in options) return this._fetchMany(options.cache); if ('cache' in options) return this._fetchMany(options.cache);
return Promise.reject(new DiscordjsError(ErrorCodes.InviteResolveCode)); throw new DiscordjsError(ErrorCodes.InviteResolveCode);
} }
return this._fetchSingle({ return this._fetchSingle({
...options, ...options,

View File

@@ -223,7 +223,7 @@ class GuildMemberManager extends CachedManager {
return this._add(data, cache); return this._add(data, cache);
} }
_fetchMany({ async _fetchMany({
limit = 0, limit = 0,
withPresences: presences, withPresences: presences,
users, users,
@@ -231,7 +231,7 @@ class GuildMemberManager extends CachedManager {
time = 120e3, time = 120e3,
nonce = DiscordSnowflake.generate().toString(), nonce = DiscordSnowflake.generate().toString(),
} = {}) { } = {}) {
if (nonce.length > 32) return Promise.reject(new DiscordjsRangeError(ErrorCodes.MemberFetchNonceLength)); if (nonce.length > 32) throw new DiscordjsRangeError(ErrorCodes.MemberFetchNonceLength);
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (!query && !users) query = ''; if (!query && !users) query = '';
@@ -461,7 +461,7 @@ class GuildMemberManager extends CachedManager {
*/ */
async kick(user, reason) { async kick(user, reason) {
const id = this.client.users.resolveId(user); const id = this.client.users.resolveId(user);
if (!id) return Promise.reject(new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable')); if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable');
await this.client.rest.delete(Routes.guildMember(this.guild.id, id), { reason }); await this.client.rest.delete(Routes.guildMember(this.guild.id, id), { reason });

View File

@@ -62,15 +62,13 @@ class PermissionOverwriteManager extends CachedManager {
* }, * },
* ], 'Needed to change permissions'); * ], 'Needed to change permissions');
*/ */
set(overwrites, reason) { async set(overwrites, reason) {
if (!Array.isArray(overwrites) && !(overwrites instanceof Collection)) { if (!Array.isArray(overwrites) && !(overwrites instanceof Collection)) {
return Promise.reject( throw new DiscordjsTypeError(
new DiscordjsTypeError( ErrorCodes.InvalidType,
ErrorCodes.InvalidType, 'overwrites',
'overwrites', 'Array or Collection of Permission Overwrites',
'Array or Collection of Permission Overwrites', true,
true,
),
); );
} }
return this.channel.edit({ permissionOverwrites: overwrites, reason }); return this.channel.edit({ permissionOverwrites: overwrites, reason });

View File

@@ -120,7 +120,7 @@ class Shard extends EventEmitter {
* before resolving (`-1` or `Infinity` for no wait) * before resolving (`-1` or `Infinity` for no wait)
* @returns {Promise<ChildProcess>} * @returns {Promise<ChildProcess>}
*/ */
spawn(timeout = 30_000) { async spawn(timeout = 30_000) {
if (this.process) throw new DiscordjsError(ErrorCodes.ShardingProcessExists, this.id); if (this.process) throw new DiscordjsError(ErrorCodes.ShardingProcessExists, this.id);
if (this.worker) throw new DiscordjsError(ErrorCodes.ShardingWorkerExists, this.id); if (this.worker) throw new DiscordjsError(ErrorCodes.ShardingWorkerExists, this.id);
@@ -161,7 +161,7 @@ class Shard extends EventEmitter {
*/ */
this.emit(ShardEvents.Spawn, child); this.emit(ShardEvents.Spawn, child);
if (timeout === -1 || timeout === Infinity) return Promise.resolve(child); if (timeout === -1 || timeout === Infinity) return child;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const cleanup = () => { const cleanup = () => {
clearTimeout(spawnTimeoutTimer); clearTimeout(spawnTimeoutTimer);
@@ -260,10 +260,10 @@ class Shard extends EventEmitter {
* .then(count => console.log(`${count} guilds in shard ${shard.id}`)) * .then(count => console.log(`${count} guilds in shard ${shard.id}`))
* .catch(console.error); * .catch(console.error);
*/ */
fetchClientValue(prop) { async fetchClientValue(prop) {
// Shard is dead (maybe respawning), don't cache anything and error immediately // Shard is dead (maybe respawning), don't cache anything and error immediately
if (!this.process && !this.worker) { if (!this.process && !this.worker) {
return Promise.reject(new DiscordjsError(ErrorCodes.ShardingNoChildExists, this.id)); throw new DiscordjsError(ErrorCodes.ShardingNoChildExists, this.id);
} }
// Cached promise from previous call // Cached promise from previous call
@@ -302,13 +302,13 @@ class Shard extends EventEmitter {
* @param {*} [context] The context for the eval * @param {*} [context] The context for the eval
* @returns {Promise<*>} Result of the script execution * @returns {Promise<*>} Result of the script execution
*/ */
eval(script, context) { async eval(script, context) {
// Stringify the script if it's a Function // Stringify the script if it's a Function
const _eval = typeof script === 'function' ? `(${script})(this, ${JSON.stringify(context)})` : script; const _eval = typeof script === 'function' ? `(${script})(this, ${JSON.stringify(context)})` : script;
// Shard is dead (maybe respawning), don't cache anything and error immediately // Shard is dead (maybe respawning), don't cache anything and error immediately
if (!this.process && !this.worker) { if (!this.process && !this.worker) {
return Promise.reject(new DiscordjsError(ErrorCodes.ShardingNoChildExists, this.id)); throw new DiscordjsError(ErrorCodes.ShardingNoChildExists, this.id);
} }
// Cached promise from previous call // Cached promise from previous call

View File

@@ -256,9 +256,9 @@ class ShardingManager extends EventEmitter {
* @param {BroadcastEvalOptions} [options={}] The options for the broadcast * @param {BroadcastEvalOptions} [options={}] The options for the broadcast
* @returns {Promise<*|Array<*>>} Results of the script execution * @returns {Promise<*|Array<*>>} Results of the script execution
*/ */
broadcastEval(script, options = {}) { async broadcastEval(script, options = {}) {
if (typeof script !== 'function') { if (typeof script !== 'function') {
return Promise.reject(new DiscordjsTypeError(ErrorCodes.ShardingInvalidEvalBroadcast)); throw new DiscordjsTypeError(ErrorCodes.ShardingInvalidEvalBroadcast);
} }
return this._performOnShards('eval', [`(${script})(this, ${JSON.stringify(options.context)})`], options.shard); return this._performOnShards('eval', [`(${script})(this, ${JSON.stringify(options.context)})`], options.shard);
} }
@@ -285,16 +285,16 @@ class ShardingManager extends EventEmitter {
* @returns {Promise<*|Array<*>>} Results of the method execution * @returns {Promise<*|Array<*>>} Results of the method execution
* @private * @private
*/ */
_performOnShards(method, args, shard) { async _performOnShards(method, args, shard) {
if (this.shards.size === 0) return Promise.reject(new DiscordjsError(ErrorCodes.ShardingNoShards)); if (this.shards.size === 0) throw new DiscordjsError(ErrorCodes.ShardingNoShards);
if (typeof shard === 'number') { if (typeof shard === 'number') {
if (this.shards.has(shard)) return this.shards.get(shard)[method](...args); if (this.shards.has(shard)) return this.shards.get(shard)[method](...args);
return Promise.reject(new DiscordjsError(ErrorCodes.ShardingShardNotFound, shard)); throw new DiscordjsError(ErrorCodes.ShardingShardNotFound, shard);
} }
if (this.shards.size !== this.shardList.length) { if (this.shards.size !== this.shardList.length) {
return Promise.reject(new DiscordjsError(ErrorCodes.ShardingInProcess)); throw new DiscordjsError(ErrorCodes.ShardingInProcess);
} }
const promises = []; const promises = [];

View File

@@ -265,8 +265,8 @@ class GuildChannel extends BaseChannel {
* Locks in the permission overwrites from the parent channel. * Locks in the permission overwrites from the parent channel.
* @returns {Promise<GuildChannel>} * @returns {Promise<GuildChannel>}
*/ */
lockPermissions() { async lockPermissions() {
if (!this.parent) return Promise.reject(new DiscordjsError(ErrorCodes.GuildChannelOrphan)); if (!this.parent) throw new DiscordjsError(ErrorCodes.GuildChannelOrphan);
const permissionOverwrites = this.parent.permissionOverwrites.cache.map(overwrite => overwrite.toJSON()); const permissionOverwrites = this.parent.permissionOverwrites.cache.map(overwrite => overwrite.toJSON());
return this.edit({ permissionOverwrites }); return this.edit({ permissionOverwrites });
} }

View File

@@ -824,8 +824,8 @@ class Message extends Base {
* .then(msg => console.log(`Updated the content of a message to ${msg.content}`)) * .then(msg => console.log(`Updated the content of a message to ${msg.content}`))
* .catch(console.error); * .catch(console.error);
*/ */
edit(options) { async edit(options) {
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached)); if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
return this.channel.messages.edit(this, options); return this.channel.messages.edit(this, options);
} }
@@ -840,8 +840,8 @@ class Message extends Base {
* .catch(console.error); * .catch(console.error);
* } * }
*/ */
crosspost() { async crosspost() {
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached)); if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
return this.channel.messages.crosspost(this.id); return this.channel.messages.crosspost(this.id);
} }
@@ -939,8 +939,8 @@ class Message extends Base {
* .then(() => console.log(`Replied to message "${message.content}"`)) * .then(() => console.log(`Replied to message "${message.content}"`))
* .catch(console.error); * .catch(console.error);
*/ */
reply(options) { async reply(options) {
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached)); if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
let data; let data;
if (options instanceof MessagePayload) { if (options instanceof MessagePayload) {
@@ -972,12 +972,12 @@ class Message extends Base {
* @param {StartThreadOptions} [options] Options for starting a thread on this message * @param {StartThreadOptions} [options] Options for starting a thread on this message
* @returns {Promise<ThreadChannel>} * @returns {Promise<ThreadChannel>}
*/ */
startThread(options = {}) { async startThread(options = {}) {
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached)); if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
if (![ChannelType.GuildText, ChannelType.GuildAnnouncement].includes(this.channel.type)) { if (![ChannelType.GuildText, ChannelType.GuildAnnouncement].includes(this.channel.type)) {
return Promise.reject(new DiscordjsError(ErrorCodes.MessageThreadParent)); throw new DiscordjsError(ErrorCodes.MessageThreadParent);
} }
if (this.hasThread) return Promise.reject(new DiscordjsError(ErrorCodes.MessageExistingThread)); if (this.hasThread) throw new DiscordjsError(ErrorCodes.MessageExistingThread);
return this.channel.threads.create({ ...options, startMessage: this }); return this.channel.threads.create({ ...options, startMessage: this });
} }
@@ -986,8 +986,8 @@ class Message extends Base {
* @param {boolean} [force=true] Whether to skip the cache check and request the API * @param {boolean} [force=true] Whether to skip the cache check and request the API
* @returns {Promise<Message>} * @returns {Promise<Message>}
*/ */
fetch(force = true) { async fetch(force = true) {
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached)); if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
return this.channel.messages.fetch({ message: this.id, force }); return this.channel.messages.fetch({ message: this.id, force });
} }
@@ -995,9 +995,9 @@ class Message extends Base {
* Fetches the webhook used to create this message. * Fetches the webhook used to create this message.
* @returns {Promise<?Webhook>} * @returns {Promise<?Webhook>}
*/ */
fetchWebhook() { async fetchWebhook() {
if (!this.webhookId) return Promise.reject(new DiscordjsError(ErrorCodes.WebhookMessage)); if (!this.webhookId) throw new DiscordjsError(ErrorCodes.WebhookMessage);
if (this.webhookId === this.applicationId) return Promise.reject(new DiscordjsError(ErrorCodes.WebhookApplication)); if (this.webhookId === this.applicationId) throw new DiscordjsError(ErrorCodes.WebhookApplication);
return this.client.fetchWebhook(this.webhookId); return this.client.fetchWebhook(this.webhookId);
} }

View File

@@ -100,12 +100,12 @@ class PartialGroupDMChannel extends BaseChannel {
return this.client.users.fetch(this.ownerId, options); return this.client.users.fetch(this.ownerId, options);
} }
delete() { async delete() {
return Promise.reject(new DiscordjsError(ErrorCodes.DeleteGroupDMChannel)); throw new DiscordjsError(ErrorCodes.DeleteGroupDMChannel);
} }
fetch() { async fetch() {
return Promise.reject(new DiscordjsError(ErrorCodes.FetchGroupDMChannel)); throw new DiscordjsError(ErrorCodes.FetchGroupDMChannel);
} }
// These are here only for documentation purposes - they are implemented by TextBasedChannel // These are here only for documentation purposes - they are implemented by TextBasedChannel

View File

@@ -97,9 +97,9 @@ class Poll extends Base {
* Ends this poll. * Ends this poll.
* @returns {Promise<Message>} * @returns {Promise<Message>}
*/ */
end() { async end() {
if (Date.now() > this.expiresTimestamp) { if (Date.now() > this.expiresTimestamp) {
return Promise.reject(new DiscordjsError(ErrorCodes.PollAlreadyExpired)); throw new DiscordjsError(ErrorCodes.PollAlreadyExpired);
} }
return this.message.channel.messages.endPoll(this.message.id); return this.message.channel.messages.endPoll(this.message.id);

View File

@@ -182,8 +182,8 @@ class Sticker extends Base {
* Fetches the pack that contains this sticker. * Fetches the pack that contains this sticker.
* @returns {Promise<?StickerPack>} The sticker pack or `null` if this sticker does not belong to one. * @returns {Promise<?StickerPack>} The sticker pack or `null` if this sticker does not belong to one.
*/ */
fetchPack() { async fetchPack() {
if (!this.packId) return Promise.resolve(null); if (!this.packId) return null;
return this.client.fetchStickerPacks({ packId: this.packId }); return this.client.fetchStickerPacks({ packId: this.packId });
} }

View File

@@ -317,7 +317,6 @@ class ThreadChannel extends BaseChannel {
* @param {BaseFetchOptions} [options] Additional options for this fetch * @param {BaseFetchOptions} [options] Additional options for this fetch
* @returns {Promise<?Message<true>>} * @returns {Promise<?Message<true>>}
*/ */
// eslint-disable-next-line require-await
async fetchStarterMessage(options) { async fetchStarterMessage(options) {
const channel = this.parent instanceof getThreadOnlyChannel() ? this : this.parent; const channel = this.parent instanceof getThreadOnlyChannel() ? this : this.parent;
return channel?.messages.fetch({ message: this.id, ...options }) ?? null; return channel?.messages.fetch({ message: this.id, ...options }) ?? null;
@@ -407,9 +406,9 @@ class ThreadChannel extends BaseChannel {
* @param {string} [reason] Reason for changing invite * @param {string} [reason] Reason for changing invite
* @returns {Promise<ThreadChannel>} * @returns {Promise<ThreadChannel>}
*/ */
setInvitable(invitable = true, reason) { async setInvitable(invitable = true, reason) {
if (this.type !== ChannelType.PrivateThread) { if (this.type !== ChannelType.PrivateThread) {
return Promise.reject(new DiscordjsRangeError(ErrorCodes.ThreadInvitableType, this.type)); throw new DiscordjsRangeError(ErrorCodes.ThreadInvitableType, this.type);
} }
return this.edit({ invitable, reason }); return this.edit({ invitable, reason });
} }

View File

@@ -273,7 +273,7 @@ class InteractionResponses {
* @returns {Promise<Message>} * @returns {Promise<Message>}
*/ */
async followUp(options) { async followUp(options) {
if (!this.deferred && !this.replied) return Promise.reject(new DiscordjsError(ErrorCodes.InteractionNotReplied)); if (!this.deferred && !this.replied) throw new DiscordjsError(ErrorCodes.InteractionNotReplied);
const msg = await this.webhook.send(options); const msg = await this.webhook.send(options);
this.replied = true; this.replied = true;
return msg; return msg;
@@ -427,7 +427,7 @@ class InteractionResponses {
* .then(interaction => console.log(`${interaction.customId} was submitted!`)) * .then(interaction => console.log(`${interaction.customId} was submitted!`))
* .catch(console.error); * .catch(console.error);
*/ */
awaitModalSubmit(options) { async awaitModalSubmit(options) {
if (typeof options.time !== 'number') throw new DiscordjsError(ErrorCodes.InvalidType, 'time', 'number'); if (typeof options.time !== 'number') throw new DiscordjsError(ErrorCodes.InvalidType, 'time', 'number');
const _options = { ...options, max: 1, interactionType: InteractionType.ModalSubmit }; const _options = { ...options, max: 1, interactionType: InteractionType.ModalSubmit };
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {