mirror of
https://github.com/discordjs/discord.js.git
synced 2026-03-09 16:13:31 +01:00
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:
@@ -83,7 +83,7 @@
|
||||
"no-void": "error",
|
||||
"no-warning-comments": "warn",
|
||||
"prefer-promise-reject-errors": "error",
|
||||
"require-await": "warn",
|
||||
"require-await": "off",
|
||||
"wrap-iife": "error",
|
||||
"yoda": "error",
|
||||
|
||||
|
||||
@@ -94,14 +94,14 @@ class GuildBanManager extends CachedManager {
|
||||
* .then(console.log)
|
||||
* .catch(console.error);
|
||||
*/
|
||||
fetch(options) {
|
||||
async fetch(options) {
|
||||
if (!options) return this._fetchMany();
|
||||
const { user, cache, force, limit, before, after } = options;
|
||||
const resolvedUser = this.client.users.resolveId(user ?? options);
|
||||
if (resolvedUser) return this._fetchSingle({ user: resolvedUser, cache, force });
|
||||
|
||||
if (!before && !after && !limit && cache === undefined) {
|
||||
return Promise.reject(new DiscordjsError(ErrorCodes.FetchBanResolveId));
|
||||
throw new DiscordjsError(ErrorCodes.FetchBanResolveId);
|
||||
}
|
||||
|
||||
return this._fetchMany(options);
|
||||
|
||||
@@ -39,14 +39,14 @@ class GuildEmojiRoleManager extends DataManager {
|
||||
* @param {RoleResolvable|RoleResolvable[]|Collection<Snowflake, Role>} roleOrRoles The role or roles to add
|
||||
* @returns {Promise<GuildEmoji>}
|
||||
*/
|
||||
add(roleOrRoles) {
|
||||
async add(roleOrRoles) {
|
||||
if (!Array.isArray(roleOrRoles) && !(roleOrRoles instanceof Collection)) roleOrRoles = [roleOrRoles];
|
||||
|
||||
const resolvedRoles = [];
|
||||
for (const role of roleOrRoles.values()) {
|
||||
const resolvedRole = this.guild.roles.resolveId(role);
|
||||
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);
|
||||
}
|
||||
@@ -60,14 +60,14 @@ class GuildEmojiRoleManager extends DataManager {
|
||||
* @param {RoleResolvable|RoleResolvable[]|Collection<Snowflake, Role>} roleOrRoles The role or roles to remove
|
||||
* @returns {Promise<GuildEmoji>}
|
||||
*/
|
||||
remove(roleOrRoles) {
|
||||
async remove(roleOrRoles) {
|
||||
if (!Array.isArray(roleOrRoles) && !(roleOrRoles instanceof Collection)) roleOrRoles = [roleOrRoles];
|
||||
|
||||
const resolvedRoleIds = [];
|
||||
for (const role of roleOrRoles.values()) {
|
||||
const roleId = this.guild.roles.resolveId(role);
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -121,22 +121,22 @@ class GuildInviteManager extends CachedManager {
|
||||
* .then(console.log)
|
||||
* .catch(console.error);
|
||||
*/
|
||||
fetch(options) {
|
||||
async fetch(options) {
|
||||
if (!options) return this._fetchMany();
|
||||
if (typeof options === 'string') {
|
||||
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 });
|
||||
}
|
||||
if (!options.code) {
|
||||
if (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);
|
||||
}
|
||||
|
||||
if ('cache' in options) return this._fetchMany(options.cache);
|
||||
return Promise.reject(new DiscordjsError(ErrorCodes.InviteResolveCode));
|
||||
throw new DiscordjsError(ErrorCodes.InviteResolveCode);
|
||||
}
|
||||
return this._fetchSingle({
|
||||
...options,
|
||||
|
||||
@@ -223,7 +223,7 @@ class GuildMemberManager extends CachedManager {
|
||||
return this._add(data, cache);
|
||||
}
|
||||
|
||||
_fetchMany({
|
||||
async _fetchMany({
|
||||
limit = 0,
|
||||
withPresences: presences,
|
||||
users,
|
||||
@@ -231,7 +231,7 @@ class GuildMemberManager extends CachedManager {
|
||||
time = 120e3,
|
||||
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) => {
|
||||
if (!query && !users) query = '';
|
||||
@@ -461,7 +461,7 @@ class GuildMemberManager extends CachedManager {
|
||||
*/
|
||||
async kick(user, reason) {
|
||||
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 });
|
||||
|
||||
|
||||
@@ -62,15 +62,13 @@ class PermissionOverwriteManager extends CachedManager {
|
||||
* },
|
||||
* ], 'Needed to change permissions');
|
||||
*/
|
||||
set(overwrites, reason) {
|
||||
async set(overwrites, reason) {
|
||||
if (!Array.isArray(overwrites) && !(overwrites instanceof Collection)) {
|
||||
return Promise.reject(
|
||||
new DiscordjsTypeError(
|
||||
ErrorCodes.InvalidType,
|
||||
'overwrites',
|
||||
'Array or Collection of Permission Overwrites',
|
||||
true,
|
||||
),
|
||||
throw new DiscordjsTypeError(
|
||||
ErrorCodes.InvalidType,
|
||||
'overwrites',
|
||||
'Array or Collection of Permission Overwrites',
|
||||
true,
|
||||
);
|
||||
}
|
||||
return this.channel.edit({ permissionOverwrites: overwrites, reason });
|
||||
|
||||
@@ -120,7 +120,7 @@ class Shard extends AsyncEventEmitter {
|
||||
* before resolving (`-1` or `Infinity` for no wait)
|
||||
* @returns {Promise<ChildProcess>}
|
||||
*/
|
||||
spawn(timeout = 30_000) {
|
||||
async spawn(timeout = 30_000) {
|
||||
if (this.process) throw new DiscordjsError(ErrorCodes.ShardingProcessExists, this.id);
|
||||
if (this.worker) throw new DiscordjsError(ErrorCodes.ShardingWorkerExists, this.id);
|
||||
|
||||
@@ -161,7 +161,7 @@ class Shard extends AsyncEventEmitter {
|
||||
*/
|
||||
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) => {
|
||||
const cleanup = () => {
|
||||
clearTimeout(spawnTimeoutTimer);
|
||||
@@ -260,10 +260,10 @@ class Shard extends AsyncEventEmitter {
|
||||
* .then(count => console.log(`${count} guilds in shard ${shard.id}`))
|
||||
* .catch(console.error);
|
||||
*/
|
||||
fetchClientValue(prop) {
|
||||
async fetchClientValue(prop) {
|
||||
// Shard is dead (maybe respawning), don't cache anything and error immediately
|
||||
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
|
||||
@@ -302,13 +302,13 @@ class Shard extends AsyncEventEmitter {
|
||||
* @param {*} [context] The context for the eval
|
||||
* @returns {Promise<*>} Result of the script execution
|
||||
*/
|
||||
eval(script, context) {
|
||||
async eval(script, context) {
|
||||
// Stringify the script if it's a Function
|
||||
const _eval = typeof script === 'function' ? `(${script})(this, ${JSON.stringify(context)})` : script;
|
||||
|
||||
// Shard is dead (maybe respawning), don't cache anything and error immediately
|
||||
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
|
||||
|
||||
@@ -256,9 +256,9 @@ class ShardingManager extends AsyncEventEmitter {
|
||||
* @param {BroadcastEvalOptions} [options={}] The options for the broadcast
|
||||
* @returns {Promise<*|Array<*>>} Results of the script execution
|
||||
*/
|
||||
broadcastEval(script, options = {}) {
|
||||
async broadcastEval(script, options = {}) {
|
||||
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);
|
||||
}
|
||||
@@ -285,16 +285,16 @@ class ShardingManager extends AsyncEventEmitter {
|
||||
* @returns {Promise<*|Array<*>>} Results of the method execution
|
||||
* @private
|
||||
*/
|
||||
_performOnShards(method, args, shard) {
|
||||
if (this.shards.size === 0) return Promise.reject(new DiscordjsError(ErrorCodes.ShardingNoShards));
|
||||
async _performOnShards(method, args, shard) {
|
||||
if (this.shards.size === 0) throw new DiscordjsError(ErrorCodes.ShardingNoShards);
|
||||
|
||||
if (typeof shard === 'number') {
|
||||
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) {
|
||||
return Promise.reject(new DiscordjsError(ErrorCodes.ShardingInProcess));
|
||||
throw new DiscordjsError(ErrorCodes.ShardingInProcess);
|
||||
}
|
||||
|
||||
const promises = [];
|
||||
|
||||
@@ -265,8 +265,8 @@ class GuildChannel extends BaseChannel {
|
||||
* Locks in the permission overwrites from the parent channel.
|
||||
* @returns {Promise<GuildChannel>}
|
||||
*/
|
||||
lockPermissions() {
|
||||
if (!this.parent) return Promise.reject(new DiscordjsError(ErrorCodes.GuildChannelOrphan));
|
||||
async lockPermissions() {
|
||||
if (!this.parent) throw new DiscordjsError(ErrorCodes.GuildChannelOrphan);
|
||||
const permissionOverwrites = this.parent.permissionOverwrites.cache.map(overwrite => overwrite.toJSON());
|
||||
return this.edit({ permissionOverwrites });
|
||||
}
|
||||
|
||||
@@ -796,8 +796,8 @@ class Message extends Base {
|
||||
* .then(msg => console.log(`Updated the content of a message to ${msg.content}`))
|
||||
* .catch(console.error);
|
||||
*/
|
||||
edit(options) {
|
||||
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
|
||||
async edit(options) {
|
||||
if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
|
||||
return this.channel.messages.edit(this, options);
|
||||
}
|
||||
|
||||
@@ -812,8 +812,8 @@ class Message extends Base {
|
||||
* .catch(console.error);
|
||||
* }
|
||||
*/
|
||||
crosspost() {
|
||||
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
|
||||
async crosspost() {
|
||||
if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
|
||||
return this.channel.messages.crosspost(this.id);
|
||||
}
|
||||
|
||||
@@ -911,8 +911,8 @@ class Message extends Base {
|
||||
* .then(() => console.log(`Replied to message "${message.content}"`))
|
||||
* .catch(console.error);
|
||||
*/
|
||||
reply(options) {
|
||||
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
|
||||
async reply(options) {
|
||||
if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
|
||||
let data;
|
||||
|
||||
if (options instanceof MessagePayload) {
|
||||
@@ -944,12 +944,12 @@ class Message extends Base {
|
||||
* @param {StartThreadOptions} [options] Options for starting a thread on this message
|
||||
* @returns {Promise<ThreadChannel>}
|
||||
*/
|
||||
startThread(options = {}) {
|
||||
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
|
||||
async startThread(options = {}) {
|
||||
if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
|
||||
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 });
|
||||
}
|
||||
|
||||
@@ -958,8 +958,8 @@ class Message extends Base {
|
||||
* @param {boolean} [force=true] Whether to skip the cache check and request the API
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
fetch(force = true) {
|
||||
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
|
||||
async fetch(force = true) {
|
||||
if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
|
||||
return this.channel.messages.fetch({ message: this.id, force });
|
||||
}
|
||||
|
||||
@@ -967,9 +967,9 @@ class Message extends Base {
|
||||
* Fetches the webhook used to create this message.
|
||||
* @returns {Promise<?Webhook>}
|
||||
*/
|
||||
fetchWebhook() {
|
||||
if (!this.webhookId) return Promise.reject(new DiscordjsError(ErrorCodes.WebhookMessage));
|
||||
if (this.webhookId === this.applicationId) return Promise.reject(new DiscordjsError(ErrorCodes.WebhookApplication));
|
||||
async fetchWebhook() {
|
||||
if (!this.webhookId) throw new DiscordjsError(ErrorCodes.WebhookMessage);
|
||||
if (this.webhookId === this.applicationId) throw new DiscordjsError(ErrorCodes.WebhookApplication);
|
||||
return this.client.fetchWebhook(this.webhookId);
|
||||
}
|
||||
|
||||
|
||||
@@ -100,12 +100,12 @@ class PartialGroupDMChannel extends BaseChannel {
|
||||
return this.client.users.fetch(this.ownerId, options);
|
||||
}
|
||||
|
||||
delete() {
|
||||
return Promise.reject(new DiscordjsError(ErrorCodes.DeleteGroupDMChannel));
|
||||
async delete() {
|
||||
throw new DiscordjsError(ErrorCodes.DeleteGroupDMChannel);
|
||||
}
|
||||
|
||||
fetch() {
|
||||
return Promise.reject(new DiscordjsError(ErrorCodes.FetchGroupDMChannel));
|
||||
async fetch() {
|
||||
throw new DiscordjsError(ErrorCodes.FetchGroupDMChannel);
|
||||
}
|
||||
|
||||
// These are here only for documentation purposes - they are implemented by TextBasedChannel
|
||||
|
||||
@@ -97,9 +97,9 @@ class Poll extends Base {
|
||||
* Ends this poll.
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
end() {
|
||||
async end() {
|
||||
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);
|
||||
|
||||
@@ -182,8 +182,8 @@ class Sticker extends Base {
|
||||
* Fetches the pack that contains this sticker.
|
||||
* @returns {Promise<?StickerPack>} The sticker pack or `null` if this sticker does not belong to one.
|
||||
*/
|
||||
fetchPack() {
|
||||
if (!this.packId) return Promise.resolve(null);
|
||||
async fetchPack() {
|
||||
if (!this.packId) return null;
|
||||
return this.client.fetchStickerPacks({ packId: this.packId });
|
||||
}
|
||||
|
||||
|
||||
@@ -308,7 +308,6 @@ class ThreadChannel extends BaseChannel {
|
||||
* @param {BaseFetchOptions} [options] Additional options for this fetch
|
||||
* @returns {Promise<?Message<true>>}
|
||||
*/
|
||||
// eslint-disable-next-line require-await
|
||||
async fetchStarterMessage(options) {
|
||||
const channel = this.parent instanceof getThreadOnlyChannel() ? this : this.parent;
|
||||
return channel?.messages.fetch({ message: this.id, ...options }) ?? null;
|
||||
@@ -398,9 +397,9 @@ class ThreadChannel extends BaseChannel {
|
||||
* @param {string} [reason] Reason for changing invite
|
||||
* @returns {Promise<ThreadChannel>}
|
||||
*/
|
||||
setInvitable(invitable = true, reason) {
|
||||
async setInvitable(invitable = true, reason) {
|
||||
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 });
|
||||
}
|
||||
|
||||
@@ -199,7 +199,7 @@ class InteractionResponses {
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
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);
|
||||
this.replied = true;
|
||||
return msg;
|
||||
@@ -305,7 +305,7 @@ class InteractionResponses {
|
||||
* .then(interaction => console.log(`${interaction.customId} was submitted!`))
|
||||
* .catch(console.error);
|
||||
*/
|
||||
awaitModalSubmit(options) {
|
||||
async awaitModalSubmit(options) {
|
||||
if (typeof options.time !== 'number') throw new DiscordjsError(ErrorCodes.InvalidType, 'time', 'number');
|
||||
const _options = { ...options, max: 1, interactionType: InteractionType.ModalSubmit };
|
||||
return new Promise((resolve, reject) => {
|
||||
|
||||
Reference in New Issue
Block a user