refactor: rename Error to DiscordjsError internally (#8706)

* refactor: rename Error to DiscordjsError internally

* chore: remove globalThis usage

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
This commit is contained in:
Almeida
2022-10-06 10:21:03 +01:00
committed by GitHub
parent e745b95677
commit aec44a0c93
60 changed files with 335 additions and 307 deletions

View File

@@ -2,7 +2,7 @@
const EventEmitter = require('node:events');
const { REST } = require('@discordjs/rest');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const Options = require('../util/Options');
const { mergeDefault, flatten } = require('../util/Util');
@@ -15,7 +15,7 @@ class BaseClient extends EventEmitter {
super({ captureRejections: true });
if (typeof options !== 'object' || options === null) {
throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
}
/**

View File

@@ -8,7 +8,7 @@ const BaseClient = require('./BaseClient');
const ActionsManager = require('./actions/ActionsManager');
const ClientVoiceManager = require('./voice/ClientVoiceManager');
const WebSocketManager = require('./websocket/WebSocketManager');
const { Error, TypeError, RangeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, DiscordjsRangeError, ErrorCodes } = require('../errors');
const BaseGuildEmojiManager = require('../managers/BaseGuildEmojiManager');
const ChannelManager = require('../managers/ChannelManager');
const GuildManager = require('../managers/GuildManager');
@@ -211,7 +211,7 @@ class Client extends BaseClient {
* client.login('my token');
*/
async login(token = this.token) {
if (!token || typeof token !== 'string') throw new Error(ErrorCodes.TokenInvalid);
if (!token || typeof token !== 'string') throw new DiscordjsError(ErrorCodes.TokenInvalid);
this.token = token = token.replace(/^(Bot|Bearer)\s*/i, '');
this.rest.setToken(token);
this.emit(
@@ -366,7 +366,7 @@ class Client extends BaseClient {
*/
async fetchGuildPreview(guild) {
const id = this.guilds.resolveId(guild);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable');
const data = await this.rest.get(Routes.guildPreview(id));
return new GuildPreview(this, data);
}
@@ -378,7 +378,7 @@ class Client extends BaseClient {
*/
async fetchGuildWidget(guild) {
const id = this.guilds.resolveId(guild);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable');
const data = await this.rest.get(Routes.guildWidgetJSON(id));
return new Widget(this, data);
}
@@ -413,23 +413,23 @@ class Client extends BaseClient {
* console.log(`Generated bot invite link: ${link}`);
*/
generateInvite(options = {}) {
if (typeof options !== 'object') throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (!this.application) throw new Error(ErrorCodes.ClientNotReady, 'generate an invite link');
if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (!this.application) throw new DiscordjsError(ErrorCodes.ClientNotReady, 'generate an invite link');
const { scopes } = options;
if (typeof scopes === 'undefined') {
throw new TypeError(ErrorCodes.InvalidMissingScopes);
throw new DiscordjsTypeError(ErrorCodes.InvalidMissingScopes);
}
if (!Array.isArray(scopes)) {
throw new TypeError(ErrorCodes.InvalidType, 'scopes', 'Array of Invite Scopes', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'scopes', 'Array of Invite Scopes', true);
}
if (!scopes.some(scope => [OAuth2Scopes.Bot, OAuth2Scopes.ApplicationsCommands].includes(scope))) {
throw new TypeError(ErrorCodes.InvalidMissingScopes);
throw new DiscordjsTypeError(ErrorCodes.InvalidMissingScopes);
}
const validScopes = Object.values(OAuth2Scopes);
const invalidScope = scopes.find(scope => !validScopes.includes(scope));
if (invalidScope) {
throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'scopes', invalidScope);
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'scopes', invalidScope);
}
const query = makeURLSearchParams({
@@ -445,7 +445,7 @@ class Client extends BaseClient {
if (options.guild) {
const guildId = this.guilds.resolveId(options.guild);
if (!guildId) throw new TypeError(ErrorCodes.InvalidType, 'options.guild', 'GuildResolvable');
if (!guildId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options.guild', 'GuildResolvable');
query.set('guild_id', guildId);
}
@@ -477,31 +477,31 @@ class Client extends BaseClient {
*/
_validateOptions(options = this.options) {
if (typeof options.intents === 'undefined') {
throw new TypeError(ErrorCodes.ClientMissingIntents);
throw new DiscordjsTypeError(ErrorCodes.ClientMissingIntents);
} else {
options.intents = IntentsBitField.resolve(options.intents);
}
if (typeof options.shardCount !== 'number' || isNaN(options.shardCount) || options.shardCount < 1) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'shardCount', 'a number greater than or equal to 1');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'shardCount', 'a number greater than or equal to 1');
}
if (options.shards && !(options.shards === 'auto' || Array.isArray(options.shards))) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'shards', "'auto', a number or array of numbers");
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'shards', "'auto', a number or array of numbers");
}
if (options.shards && !options.shards.length) throw new RangeError(ErrorCodes.ClientInvalidProvidedShards);
if (options.shards && !options.shards.length) throw new DiscordjsRangeError(ErrorCodes.ClientInvalidProvidedShards);
if (typeof options.makeCache !== 'function') {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'makeCache', 'a function');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'makeCache', 'a function');
}
if (typeof options.sweepers !== 'object' || options.sweepers === null) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'sweepers', 'an object');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'sweepers', 'an object');
}
if (!Array.isArray(options.partials)) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'partials', 'an Array');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'partials', 'an Array');
}
if (typeof options.waitGuildTimeout !== 'number' || isNaN(options.waitGuildTimeout)) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'waitGuildTimeout', 'a number');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'waitGuildTimeout', 'a number');
}
if (typeof options.failIfNotExists !== 'boolean') {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'failIfNotExists', 'a boolean');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'failIfNotExists', 'a boolean');
}
}
}

View File

@@ -1,7 +1,7 @@
'use strict';
const BaseClient = require('./BaseClient');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const Webhook = require('../structures/Webhook');
const { parseWebhookURL } = require('../util/Util');
@@ -48,7 +48,7 @@ class WebhookClient extends BaseClient {
if ('url' in data) {
const parsed = parseWebhookURL(data.url);
if (!parsed) {
throw new Error(ErrorCodes.WebhookURLInvalid);
throw new DiscordjsError(ErrorCodes.WebhookURLInvalid);
}
({ id, token } = parsed);

View File

@@ -7,7 +7,7 @@ const { Collection } = require('@discordjs/collection');
const { GatewayCloseCodes, GatewayDispatchEvents, Routes } = require('discord-api-types/v10');
const WebSocketShard = require('./WebSocketShard');
const PacketHandlers = require('./handlers');
const { Error, ErrorCodes } = require('../../errors');
const { DiscordjsError, ErrorCodes } = require('../../errors');
const Events = require('../../util/Events');
const Status = require('../../util/Status');
const WebSocketShardEvents = require('../../util/WebSocketShardEvents');
@@ -131,7 +131,7 @@ class WebSocketManager extends EventEmitter {
* @private
*/
async connect() {
const invalidToken = new Error(ErrorCodes.TokenInvalid);
const invalidToken = new DiscordjsError(ErrorCodes.TokenInvalid);
const {
url: gatewayURL,
shards: recommendedShards,
@@ -247,7 +247,7 @@ class WebSocketManager extends EventEmitter {
await shard.connect();
} catch (error) {
if (error?.code && error.code in unrecoverableErrorCodeMap) {
throw new Error(unrecoverableErrorCodeMap[error.code]);
throw new DiscordjsError(unrecoverableErrorCodeMap[error.code]);
// Undefined if session is invalid, error event for regular closes
} else if (!error || error.code) {
this.debug('Failed to connect to the gateway, requeueing...', shard);
@@ -320,7 +320,7 @@ class WebSocketManager extends EventEmitter {
destroy() {
if (this.destroyed) return;
// TODO: Make a util for getting a stack
this.debug(`Manager was destroyed. Called by:\n${new globalThis.Error().stack}`);
this.debug(`Manager was destroyed. Called by:\n${new Error().stack}`);
this.destroyed = true;
this.shardQueue.clear();
for (const shard of this.shards.values()) shard.destroy({ closeCode: 1_000, reset: true, emit: false, log: false });

View File

@@ -42,7 +42,7 @@ function message(code, args) {
}
module.exports = {
Error: makeDiscordjsError(Error),
TypeError: makeDiscordjsError(TypeError),
RangeError: makeDiscordjsError(RangeError),
DiscordjsError: makeDiscordjsError(Error),
DiscordjsTypeError: makeDiscordjsError(TypeError),
DiscordjsRangeError: makeDiscordjsError(RangeError),
};

View File

@@ -11,10 +11,9 @@ exports.ShardingManager = require('./sharding/ShardingManager');
exports.WebhookClient = require('./client/WebhookClient');
// Errors
const { Error, TypeError, RangeError } = require('./errors/DJSError');
exports.DiscordjsError = Error;
exports.DiscordjsTypeError = TypeError;
exports.DiscordjsRangeError = RangeError;
exports.DiscordjsError = require('./errors/DJSError').DiscordjsError;
exports.DiscordjsTypeError = require('./errors/DJSError').DiscordjsTypeError;
exports.DiscordjsRangeError = require('./errors/DJSError').DiscordjsRangeError;
exports.DiscordjsErrorCodes = require('./errors/ErrorCodes');
// Utilities

View File

@@ -6,7 +6,7 @@ const { makeURLSearchParams } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10');
const ApplicationCommandPermissionsManager = require('./ApplicationCommandPermissionsManager');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const ApplicationCommand = require('../structures/ApplicationCommand');
const PermissionsBitField = require('../util/PermissionsBitField');
@@ -193,7 +193,7 @@ class ApplicationCommandManager extends CachedManager {
*/
async edit(command, data, guildId) {
const id = this.resolveId(command);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
const patched = await this.client.rest.patch(this.commandPath({ id, guildId }), {
body: this.constructor.transformCommand(data),
@@ -215,7 +215,7 @@ class ApplicationCommandManager extends CachedManager {
*/
async delete(command, guildId) {
const id = this.resolveId(command);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
await this.client.rest.delete(this.commandPath({ id, guildId }));

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { ApplicationCommandPermissionType, RESTJSONErrorCodes, Routes } = require('discord-api-types/v10');
const BaseManager = require('./BaseManager');
const { Error, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* Manages API methods for permissions of Application Commands.
@@ -153,12 +153,17 @@ class ApplicationCommandPermissionsManager extends BaseManager {
*/
async set({ guild, command, permissions, token } = {}) {
if (!token) {
throw new Error(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
}
let { guildId, commandId } = this._validateOptions(guild, command);
if (!Array.isArray(permissions)) {
throw new TypeError(ErrorCodes.InvalidType, 'permissions', 'Array of ApplicationCommandPermissions', true);
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'permissions',
'Array of ApplicationCommandPermissions',
true,
);
}
if (!commandId) {
@@ -190,14 +195,19 @@ class ApplicationCommandPermissionsManager extends BaseManager {
*/
async add({ guild, command, permissions, token } = {}) {
if (!token) {
throw new Error(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
}
let { guildId, commandId } = this._validateOptions(guild, command);
if (!commandId) {
commandId = this.client.user.id;
}
if (!Array.isArray(permissions)) {
throw new TypeError(ErrorCodes.InvalidType, 'permissions', 'Array of ApplicationCommandPermissions', true);
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'permissions',
'Array of ApplicationCommandPermissions',
true,
);
}
let existing = [];
@@ -262,7 +272,7 @@ class ApplicationCommandPermissionsManager extends BaseManager {
*/
async remove({ guild, command, users, roles, channels, token } = {}) {
if (!token) {
throw new Error(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
}
let { guildId, commandId } = this._validateOptions(guild, command);
if (!commandId) {
@@ -270,14 +280,14 @@ class ApplicationCommandPermissionsManager extends BaseManager {
}
if (!users && !roles && !channels) {
throw new TypeError(ErrorCodes.InvalidType, 'users OR roles OR channels', 'Array or Resolvable', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'users OR roles OR channels', 'Array or Resolvable', true);
}
let resolvedUserIds = [];
if (Array.isArray(users)) {
for (const user of users) {
const userId = this.client.users.resolveId(user);
if (!userId) throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'users', user);
if (!userId) throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'users', user);
resolvedUserIds.push(userId);
}
}
@@ -289,9 +299,9 @@ class ApplicationCommandPermissionsManager extends BaseManager {
resolvedRoleIds.push(role);
continue;
}
if (!this.guild) throw new Error(ErrorCodes.GuildUncachedEntityResolve, 'roles');
if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'roles');
const roleId = this.guild.roles.resolveId(role);
if (!roleId) throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'users', role);
if (!roleId) throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'users', role);
resolvedRoleIds.push(roleId);
}
}
@@ -303,9 +313,9 @@ class ApplicationCommandPermissionsManager extends BaseManager {
resolvedChannelIds.push(channel);
continue;
}
if (!this.guild) throw new Error(ErrorCodes.GuildUncachedEntityResolve, 'channels');
if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'channels');
const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'channels', channel);
if (!channelId) throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'channels', channel);
resolvedChannelIds.push(channelId);
}
}
@@ -353,10 +363,10 @@ class ApplicationCommandPermissionsManager extends BaseManager {
*/
async has({ guild, command, permissionId, permissionType }) {
const { guildId, commandId } = this._validateOptions(guild, command);
if (!commandId) throw new TypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
if (!commandId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
if (!permissionId) {
throw new TypeError(
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'permissionId',
'UserResolvable, RoleResolvable, ChannelResolvable, or Permission Constant',
@@ -366,14 +376,14 @@ class ApplicationCommandPermissionsManager extends BaseManager {
if (typeof permissionId !== 'string') {
resolvedId = this.client.users.resolveId(permissionId);
if (!resolvedId) {
if (!this.guild) throw new Error(ErrorCodes.GuildUncachedEntityResolve, 'roles');
if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'roles');
resolvedId = this.guild.roles.resolveId(permissionId);
}
if (!resolvedId) {
resolvedId = this.guild.channels.resolveId(permissionId);
}
if (!resolvedId) {
throw new TypeError(
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'permissionId',
'UserResolvable, RoleResolvable, ChannelResolvable, or Permission Constant',
@@ -394,7 +404,7 @@ class ApplicationCommandPermissionsManager extends BaseManager {
_validateOptions(guild, command) {
const guildId = this.guildId ?? this.client.guilds.resolveId(guild);
if (!guildId) throw new Error(ErrorCodes.GlobalCommandPermissions);
if (!guildId) throw new DiscordjsError(ErrorCodes.GlobalCommandPermissions);
let commandId = this.commandId;
if (command && !commandId) {
commandId = this.manager.resolveId?.(command);
@@ -403,7 +413,7 @@ class ApplicationCommandPermissionsManager extends BaseManager {
}
commandId ??= this.client.application?.commands.resolveId(command);
if (!commandId) {
throw new TypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable', true);
}
}
return { guildId, commandId };

View File

@@ -1,7 +1,7 @@
'use strict';
const BaseManager = require('./BaseManager');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Manages the API methods of a data model along with a collection of instances.
@@ -28,7 +28,7 @@ class DataManager extends BaseManager {
* @abstract
*/
get cache() {
throw new Error(ErrorCodes.NotImplemented, 'get cache', this.constructor.name);
throw new DiscordjsError(ErrorCodes.NotImplemented, 'get cache', this.constructor.name);
}
/**

View File

@@ -5,7 +5,7 @@ const { Collection } = require('@discordjs/collection');
const { makeURLSearchParams } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, Error, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../errors');
const GuildBan = require('../structures/GuildBan');
const { GuildMember } = require('../structures/GuildMember');
@@ -104,7 +104,7 @@ class GuildBanManager extends CachedManager {
if (resolvedUser) return this._fetchSingle({ user: resolvedUser, cache, force });
if (!before && !after && !limit && typeof cache === 'undefined') {
return Promise.reject(new Error(ErrorCodes.FetchBanResolveId));
return Promise.reject(new DiscordjsError(ErrorCodes.FetchBanResolveId));
}
return this._fetchMany(options);
@@ -152,9 +152,9 @@ class GuildBanManager extends CachedManager {
* .catch(console.error);
*/
async create(user, options = {}) {
if (typeof options !== 'object') throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
const id = this.client.users.resolveId(user);
if (!id) throw new Error(ErrorCodes.BanResolveId, true);
if (!id) throw new DiscordjsError(ErrorCodes.BanResolveId, true);
if (typeof options.deleteMessageDays !== 'undefined' && !deprecationEmittedForDeleteMessageDays) {
process.emitWarning(
@@ -195,7 +195,7 @@ class GuildBanManager extends CachedManager {
*/
async remove(user, reason) {
const id = this.client.users.resolveId(user);
if (!id) throw new Error(ErrorCodes.BanResolveId);
if (!id) throw new DiscordjsError(ErrorCodes.BanResolveId);
await this.client.rest.delete(Routes.guildBan(this.guild.id, id), { reason });
return this.client.users.resolve(user);
}

View File

@@ -5,7 +5,7 @@ const { Collection } = require('@discordjs/collection');
const { ChannelType, Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const GuildTextThreadManager = require('./GuildTextThreadManager');
const { Error, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
const GuildChannel = require('../structures/GuildChannel');
const PermissionOverwrites = require('../structures/PermissionOverwrites');
const ThreadChannel = require('../structures/ThreadChannel');
@@ -195,7 +195,7 @@ class GuildChannelManager extends CachedManager {
*/
async createWebhook({ channel, name, avatar, reason }) {
const id = this.resolveId(channel);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
if (typeof avatar === 'string' && !avatar.startsWith('data:')) {
avatar = await DataResolver.resolveImage(avatar);
}
@@ -250,7 +250,7 @@ class GuildChannelManager extends CachedManager {
*/
async edit(channel, data) {
channel = this.resolve(channel);
if (!channel) throw new TypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
if (!channel) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
const parent = data.parent && this.client.channels.resolveId(data.parent);
@@ -316,7 +316,7 @@ class GuildChannelManager extends CachedManager {
*/
async setPosition(channel, position, { relative, reason } = {}) {
channel = this.resolve(channel);
if (!channel) throw new TypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
if (!channel) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
const updatedChannels = await setPosition(
channel,
position,
@@ -359,7 +359,7 @@ class GuildChannelManager extends CachedManager {
if (id) {
const data = await this.client.rest.get(Routes.channel(id));
// Since this is the guild manager, throw if on a different guild
if (this.guild.id !== data.guild_id) throw new Error(ErrorCodes.GuildChannelUnowned);
if (this.guild.id !== data.guild_id) throw new DiscordjsError(ErrorCodes.GuildChannelUnowned);
return this.client.channels._add(data, this.guild, { cache });
}
@@ -381,7 +381,7 @@ class GuildChannelManager extends CachedManager {
*/
async fetchWebhooks(channel) {
const id = this.resolveId(channel);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
const data = await this.client.rest.get(Routes.channelWebhooks(id));
return data.reduce((hooks, hook) => hooks.set(hook.id, new Webhook(this.client, hook)), new Collection());
}
@@ -455,7 +455,7 @@ class GuildChannelManager extends CachedManager {
*/
async delete(channel, reason) {
const id = this.resolveId(channel);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
await this.client.rest.delete(Routes.channel(id), { reason });
this.client.actions.ChannelDelete.handle({ id });
}

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { Routes, PermissionFlagsBits } = require('discord-api-types/v10');
const BaseGuildEmojiManager = require('./BaseGuildEmojiManager');
const { Error, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
const DataResolver = require('../util/DataResolver');
/**
@@ -51,12 +51,12 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
*/
async create({ attachment, name, roles, reason }) {
attachment = await DataResolver.resolveImage(attachment);
if (!attachment) throw new TypeError(ErrorCodes.ReqResourceType);
if (!attachment) throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);
const body = { image: attachment, name };
if (roles) {
if (!Array.isArray(roles) && !(roles instanceof Collection)) {
throw new TypeError(
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'options.roles',
'Array or Collection of Roles or Snowflakes',
@@ -67,7 +67,7 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
for (const role of roles.values()) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) {
throw new TypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'options.roles', role);
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'options.roles', role);
}
body.roles.push(resolvedRole);
}
@@ -117,7 +117,7 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
*/
async delete(emoji, reason) {
const id = this.resolveId(emoji);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
await this.client.rest.delete(Routes.guildEmoji(this.guild.id, id), { reason });
}
@@ -129,7 +129,7 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
*/
async edit(emoji, data) {
const id = this.resolveId(emoji);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
const roles = data.roles?.map(r => this.guild.roles.resolveId(r));
const newData = await this.client.rest.patch(Routes.guildEmoji(this.guild.id, id), {
body: {
@@ -154,15 +154,15 @@ class GuildEmojiManager extends BaseGuildEmojiManager {
*/
async fetchAuthor(emoji) {
emoji = this.resolve(emoji);
if (!emoji) throw new TypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
if (!emoji) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
if (emoji.managed) {
throw new Error(ErrorCodes.EmojiManaged);
throw new DiscordjsError(ErrorCodes.EmojiManaged);
}
const { me } = this.guild.members;
if (!me) throw new Error(ErrorCodes.GuildUncachedMe);
if (!me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe);
if (!me.permissions.has(PermissionFlagsBits.ManageEmojisAndStickers)) {
throw new Error(ErrorCodes.MissingManageEmojisAndStickersPermission, this.guild);
throw new DiscordjsError(ErrorCodes.MissingManageEmojisAndStickersPermission, this.guild);
}
const data = await this.client.rest.get(Routes.guildEmoji(this.guild.id, emoji.id));

View File

@@ -2,7 +2,7 @@
const { Collection } = require('@discordjs/collection');
const DataManager = require('./DataManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const { Role } = require('../structures/Role');
/**
@@ -46,7 +46,7 @@ class GuildEmojiRoleManager extends DataManager {
for (const role of roleOrRoles.values()) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) {
return Promise.reject(new TypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role));
return Promise.reject(new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role));
}
resolvedRoles.push(resolvedRole);
}
@@ -67,7 +67,7 @@ class GuildEmojiRoleManager extends DataManager {
for (const role of roleOrRoles.values()) {
const roleId = this.guild.roles.resolveId(role);
if (!roleId) {
return Promise.reject(new TypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role));
return Promise.reject(new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role));
}
resolvedRoleIds.push(roleId);
}

View File

@@ -2,7 +2,7 @@
const { Routes } = require('discord-api-types/v10');
const ThreadManager = require('./ThreadManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const MessagePayload = require('../structures/MessagePayload');
/**
@@ -56,7 +56,7 @@ class GuildForumThreadManager extends ThreadManager {
appliedTags,
} = {}) {
if (!message) {
throw new TypeError(ErrorCodes.GuildForumMessageRequired);
throw new DiscordjsTypeError(ErrorCodes.GuildForumMessageRequired);
}
const { body, files } = await (message instanceof MessagePayload ? message : MessagePayload.create(this, message))

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const Invite = require('../structures/Invite');
const DataResolver = require('../util/DataResolver');
@@ -123,18 +123,18 @@ class GuildInviteManager extends CachedManager {
if (!options) return this._fetchMany();
if (typeof options === 'string') {
const code = DataResolver.resolveInviteCode(options);
if (!code) return Promise.reject(new Error(ErrorCodes.InviteResolveCode));
if (!code) return Promise.reject(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 Error(ErrorCodes.GuildChannelResolve));
if (!id) return Promise.reject(new DiscordjsError(ErrorCodes.GuildChannelResolve));
return this._fetchChannelMany(id, options.cache);
}
if ('cache' in options) return this._fetchMany(options.cache);
return Promise.reject(new Error(ErrorCodes.InviteResolveCode));
return Promise.reject(new DiscordjsError(ErrorCodes.InviteResolveCode));
}
return this._fetchSingle({
...options,
@@ -150,7 +150,7 @@ class GuildInviteManager extends CachedManager {
const invites = await this._fetchMany(cache);
const invite = invites.get(code);
if (!invite) throw new Error(ErrorCodes.InviteNotFound);
if (!invite) throw new DiscordjsError(ErrorCodes.InviteNotFound);
return invite;
}
@@ -180,7 +180,7 @@ class GuildInviteManager extends CachedManager {
{ temporary, maxAge, maxUses, unique, targetUser, targetApplication, targetType, reason } = {},
) {
const id = this.guild.channels.resolveId(channel);
if (!id) throw new Error(ErrorCodes.GuildChannelResolve);
if (!id) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
const invite = await this.client.rest.post(Routes.channelInvites(id), {
body: {

View File

@@ -6,7 +6,7 @@ const { makeURLSearchParams } = require('@discordjs/rest');
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { Routes, GatewayOpcodes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { Error, TypeError, RangeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, DiscordjsRangeError, ErrorCodes } = require('../errors');
const BaseGuildVoiceChannel = require('../structures/BaseGuildVoiceChannel');
const { GuildMember } = require('../structures/GuildMember');
const { Role } = require('../structures/Role');
@@ -96,7 +96,7 @@ class GuildMemberManager extends CachedManager {
*/
async add(user, options) {
const userId = this.client.users.resolveId(user);
if (!userId) throw new TypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable');
if (!userId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable');
if (!options.force) {
const cachedUser = this.cache.get(userId);
if (cachedUser) return cachedUser;
@@ -109,7 +109,7 @@ class GuildMemberManager extends CachedManager {
};
if (options.roles) {
if (!Array.isArray(options.roles) && !(options.roles instanceof Collection)) {
throw new TypeError(
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'options.roles',
'Array or Collection of Roles or Snowflakes',
@@ -120,7 +120,7 @@ class GuildMemberManager extends CachedManager {
for (const role of options.roles.values()) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) {
throw new TypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'options.roles', role);
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'options.roles', role);
}
resolvedRoles.push(resolvedRole);
}
@@ -291,12 +291,12 @@ class GuildMemberManager extends CachedManager {
*/
async edit(user, { reason, ...data }) {
const id = this.client.users.resolveId(user);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable');
if (data.channel) {
data.channel = this.guild.channels.resolve(data.channel);
if (!(data.channel instanceof BaseGuildVoiceChannel)) {
throw new Error(ErrorCodes.GuildVoiceChannelResolve);
throw new DiscordjsError(ErrorCodes.GuildVoiceChannelResolve);
}
data.channel_id = data.channel.id;
data.channel = undefined;
@@ -362,7 +362,7 @@ class GuildMemberManager extends CachedManager {
* .catch(console.error);
*/
async prune({ days, dry = false, count: compute_prune_count, roles = [], reason } = {}) {
if (typeof days !== 'number') throw new TypeError(ErrorCodes.PruneDaysType);
if (typeof days !== 'number') throw new DiscordjsTypeError(ErrorCodes.PruneDaysType);
const query = { days };
const resolvedRoles = [];
@@ -370,7 +370,7 @@ class GuildMemberManager extends CachedManager {
for (const role of roles) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) {
throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'options.roles', role);
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'options.roles', role);
}
resolvedRoles.push(resolvedRole);
}
@@ -404,7 +404,7 @@ class GuildMemberManager extends CachedManager {
*/
async kick(user, reason) {
const id = this.client.users.resolveId(user);
if (!id) return Promise.reject(new TypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable'));
if (!id) return Promise.reject(new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable'));
await this.client.rest.delete(Routes.guildMember(this.guild.id, id), { reason });
@@ -500,7 +500,7 @@ class GuildMemberManager extends CachedManager {
} = {}) {
return new Promise((resolve, reject) => {
if (!query && !user_ids) query = '';
if (nonce.length > 32) throw new RangeError(ErrorCodes.MemberFetchNonceLength);
if (nonce.length > 32) throw new DiscordjsRangeError(ErrorCodes.MemberFetchNonceLength);
this.guild.shard.send({
op: GatewayOpcodes.RequestGuildMembers,
d: {
@@ -533,7 +533,7 @@ class GuildMemberManager extends CachedManager {
const timeout = setTimeout(() => {
this.client.removeListener(Events.GuildMembersChunk, handler);
this.client.decrementMaxListeners();
reject(new Error(ErrorCodes.GuildMembersTimeout));
reject(new DiscordjsError(ErrorCodes.GuildMembersTimeout));
}, time).unref();
this.client.incrementMaxListeners();
this.client.on(Events.GuildMembersChunk, handler);

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { Routes } = require('discord-api-types/v10');
const DataManager = require('./DataManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const { Role } = require('../structures/Role');
/**
@@ -110,7 +110,9 @@ class GuildMemberRoleManager extends DataManager {
const resolvedRoles = [];
for (const role of roleOrRoles.values()) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) throw new TypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role);
if (!resolvedRole) {
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role);
}
resolvedRoles.push(resolvedRole);
}
@@ -119,7 +121,7 @@ class GuildMemberRoleManager extends DataManager {
} else {
roleOrRoles = this.guild.roles.resolveId(roleOrRoles);
if (roleOrRoles === null) {
throw new TypeError(
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'roles',
'Role, Snowflake or Array or Collection of Roles or Snowflakes',
@@ -145,7 +147,9 @@ class GuildMemberRoleManager extends DataManager {
const resolvedRoles = [];
for (const role of roleOrRoles.values()) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) throw new TypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role);
if (!resolvedRole) {
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role);
}
resolvedRoles.push(resolvedRole);
}
@@ -154,7 +158,7 @@ class GuildMemberRoleManager extends DataManager {
} else {
roleOrRoles = this.guild.roles.resolveId(roleOrRoles);
if (roleOrRoles === null) {
throw new TypeError(
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'roles',
'Role, Snowflake or Array or Collection of Roles or Snowflakes',

View File

@@ -4,7 +4,7 @@ const { Collection } = require('@discordjs/collection');
const { makeURLSearchParams } = require('@discordjs/rest');
const { GuildScheduledEventEntityType, Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, Error, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../errors');
const { GuildScheduledEvent } = require('../structures/GuildScheduledEvent');
const DataResolver = require('../util/DataResolver');
@@ -69,7 +69,7 @@ class GuildScheduledEventManager extends CachedManager {
* @returns {Promise<GuildScheduledEvent>}
*/
async create(options) {
if (typeof options !== 'object') throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
let {
privacyLevel,
entityType,
@@ -89,7 +89,7 @@ class GuildScheduledEventManager extends CachedManager {
entity_metadata = { location: entityMetadata?.location };
} else {
channel_id = this.guild.channels.resolveId(channel);
if (!channel_id) throw new Error(ErrorCodes.GuildVoiceChannelResolve);
if (!channel_id) throw new DiscordjsError(ErrorCodes.GuildVoiceChannelResolve);
entity_metadata = typeof entityMetadata === 'undefined' ? entityMetadata : null;
}
@@ -188,9 +188,9 @@ class GuildScheduledEventManager extends CachedManager {
*/
async edit(guildScheduledEvent, options) {
const guildScheduledEventId = this.resolveId(guildScheduledEvent);
if (!guildScheduledEventId) throw new Error(ErrorCodes.GuildScheduledEventResolve);
if (!guildScheduledEventId) throw new DiscordjsError(ErrorCodes.GuildScheduledEventResolve);
if (typeof options !== 'object') throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
let {
privacyLevel,
entityType,
@@ -238,7 +238,7 @@ class GuildScheduledEventManager extends CachedManager {
*/
async delete(guildScheduledEvent) {
const guildScheduledEventId = this.resolveId(guildScheduledEvent);
if (!guildScheduledEventId) throw new Error(ErrorCodes.GuildScheduledEventResolve);
if (!guildScheduledEventId) throw new DiscordjsError(ErrorCodes.GuildScheduledEventResolve);
await this.client.rest.delete(Routes.guildScheduledEvent(this.guild.id, guildScheduledEventId));
}
@@ -269,7 +269,7 @@ class GuildScheduledEventManager extends CachedManager {
*/
async fetchSubscribers(guildScheduledEvent, options = {}) {
const guildScheduledEventId = this.resolveId(guildScheduledEvent);
if (!guildScheduledEventId) throw new Error(ErrorCodes.GuildScheduledEventResolve);
if (!guildScheduledEventId) throw new DiscordjsError(ErrorCodes.GuildScheduledEventResolve);
const query = makeURLSearchParams({
limit: options.limit,

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const MessagePayload = require('../structures/MessagePayload');
const { Sticker } = require('../structures/Sticker');
@@ -59,7 +59,7 @@ class GuildStickerManager extends CachedManager {
*/
async create({ file, name, tags, description, reason } = {}) {
const resolvedFile = await MessagePayload.resolveFile(file);
if (!resolvedFile) throw new TypeError(ErrorCodes.ReqResourceType);
if (!resolvedFile) throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);
file = { ...resolvedFile, key: 'file' };
const body = { name, tags, description: description ?? '' };
@@ -106,7 +106,7 @@ class GuildStickerManager extends CachedManager {
*/
async edit(sticker, data = {}) {
const stickerId = this.resolveId(sticker);
if (!stickerId) throw new TypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
if (!stickerId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
const d = await this.client.rest.patch(Routes.guildSticker(this.guild.id, stickerId), {
body: data,
@@ -130,7 +130,7 @@ class GuildStickerManager extends CachedManager {
*/
async delete(sticker, reason) {
sticker = this.resolveId(sticker);
if (!sticker) throw new TypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
if (!sticker) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
await this.client.rest.delete(Routes.guildSticker(this.guild.id, sticker), { reason });
}
@@ -172,7 +172,7 @@ class GuildStickerManager extends CachedManager {
*/
async fetchUser(sticker) {
sticker = this.resolve(sticker);
if (!sticker) throw new TypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
if (!sticker) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
const data = await this.client.rest.get(Routes.guildSticker(this.guild.id, sticker.id));
sticker._patch(data);
return sticker.user;

View File

@@ -2,7 +2,7 @@
const { ChannelType, Routes } = require('discord-api-types/v10');
const ThreadManager = require('./ThreadManager');
const { ErrorCodes, TypeError } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* Manages API methods for {@link ThreadChannel} objects and stores their cache.
@@ -68,7 +68,7 @@ class GuildTextThreadManager extends ThreadManager {
let startMessageId;
if (startMessage) {
startMessageId = this.channel.messages.resolveId(startMessage);
if (!startMessageId) throw new TypeError(ErrorCodes.InvalidType, 'startMessage', 'MessageResolvable');
if (!startMessageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'startMessage', 'MessageResolvable');
} else if (this.channel.type !== ChannelType.GuildAnnouncement) {
resolvedType = type ?? resolvedType;
}

View File

@@ -4,7 +4,7 @@ const { Collection } = require('@discordjs/collection');
const { makeURLSearchParams } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const { Message } = require('../structures/Message');
const MessagePayload = require('../structures/MessagePayload');
const { resolvePartialEmoji } = require('../util/Util');
@@ -164,7 +164,7 @@ class MessageManager extends CachedManager {
*/
async edit(message, options) {
const messageId = this.resolveId(message);
if (!messageId) throw new TypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
const { body, files } = await (options instanceof MessagePayload
? options
@@ -190,7 +190,7 @@ class MessageManager extends CachedManager {
*/
async crosspost(message) {
message = this.resolveId(message);
if (!message) throw new TypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
const data = await this.client.rest.post(Routes.channelMessageCrosspost(this.channel.id, message));
return this.cache.get(data.id) ?? this._add(data);
@@ -204,7 +204,7 @@ class MessageManager extends CachedManager {
*/
async pin(message, reason) {
message = this.resolveId(message);
if (!message) throw new TypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
await this.client.rest.put(Routes.channelPin(this.channel.id, message), { reason });
}
@@ -217,7 +217,7 @@ class MessageManager extends CachedManager {
*/
async unpin(message, reason) {
message = this.resolveId(message);
if (!message) throw new TypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
await this.client.rest.delete(Routes.channelPin(this.channel.id, message), { reason });
}
@@ -230,10 +230,10 @@ class MessageManager extends CachedManager {
*/
async react(message, emoji) {
message = this.resolveId(message);
if (!message) throw new TypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
emoji = resolvePartialEmoji(emoji);
if (!emoji) throw new TypeError(ErrorCodes.EmojiType, 'emoji', 'EmojiIdentifierResolvable');
if (!emoji) throw new DiscordjsTypeError(ErrorCodes.EmojiType, 'emoji', 'EmojiIdentifierResolvable');
const emojiId = emoji.id
? `${emoji.animated ? 'a:' : ''}${emoji.name}:${emoji.id}`
@@ -249,7 +249,7 @@ class MessageManager extends CachedManager {
*/
async delete(message) {
message = this.resolveId(message);
if (!message) throw new TypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
await this.client.rest.delete(Routes.channelMessage(this.channel.id, message));
}

View File

@@ -4,7 +4,7 @@ const process = require('node:process');
const { Collection } = require('@discordjs/collection');
const { OverwriteType, Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const PermissionOverwrites = require('../structures/PermissionOverwrites');
const { Role } = require('../structures/Role');
@@ -65,7 +65,12 @@ class PermissionOverwriteManager extends CachedManager {
set(overwrites, reason) {
if (!Array.isArray(overwrites) && !(overwrites instanceof Collection)) {
return Promise.reject(
new TypeError(ErrorCodes.InvalidType, 'overwrites', 'Array or Collection of Permission Overwrites', true),
new DiscordjsTypeError(
ErrorCodes.InvalidType,
'overwrites',
'Array or Collection of Permission Overwrites',
true,
),
);
}
return this.channel.edit({ permissionOverwrites: overwrites, reason });
@@ -93,7 +98,7 @@ class PermissionOverwriteManager extends CachedManager {
let { type, reason } = overwriteOptions;
if (typeof type !== 'number') {
userOrRole = this.channel.guild.roles.resolve(userOrRole) ?? this.client.users.resolve(userOrRole);
if (!userOrRole) throw new TypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
if (!userOrRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
type = userOrRole instanceof Role ? OverwriteType.Role : OverwriteType.Member;
}
@@ -153,7 +158,7 @@ class PermissionOverwriteManager extends CachedManager {
*/
async delete(userOrRole, reason) {
const userOrRoleId = this.channel.guild.roles.resolveId(userOrRole) ?? this.client.users.resolveId(userOrRole);
if (!userOrRoleId) throw new TypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
if (!userOrRoleId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
await this.client.rest.delete(Routes.channelPermission(this.channel.id, userOrRoleId), { reason });
return this.channel;

View File

@@ -4,7 +4,7 @@ const { Collection } = require('@discordjs/collection');
const { makeURLSearchParams } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const User = require('../structures/User');
/**
@@ -63,7 +63,7 @@ class ReactionUserManager extends CachedManager {
*/
async remove(user = this.client.user) {
const userId = this.client.users.resolveId(user);
if (!userId) throw new Error(ErrorCodes.ReactionResolveUser);
if (!userId) throw new DiscordjsError(ErrorCodes.ReactionResolveUser);
const message = this.reaction.message;
const route =
userId === this.client.user.id

View File

@@ -4,7 +4,7 @@ const process = require('node:process');
const { Collection } = require('@discordjs/collection');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const { Role } = require('../structures/Role');
const DataResolver = require('../util/DataResolver');
const PermissionsBitField = require('../util/PermissionsBitField');
@@ -183,7 +183,7 @@ class RoleManager extends CachedManager {
*/
async edit(role, data) {
role = this.resolve(role);
if (!role) throw new TypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
if (!role) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
if (typeof data.position === 'number') {
await this.setPosition(role, data.position, { reason: data.reason });
@@ -244,7 +244,7 @@ class RoleManager extends CachedManager {
*/
async setPosition(role, position, { relative, reason } = {}) {
role = this.resolve(role);
if (!role) throw new TypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
if (!role) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
const updatedRoles = await setPosition(
role,
position,
@@ -303,7 +303,9 @@ class RoleManager extends CachedManager {
comparePositions(role1, role2) {
const resolvedRole1 = this.resolve(role1);
const resolvedRole2 = this.resolve(role2);
if (!resolvedRole1 || !resolvedRole2) throw new TypeError(ErrorCodes.InvalidType, 'role', 'Role nor a Snowflake');
if (!resolvedRole1 || !resolvedRole2) {
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'Role nor a Snowflake');
}
if (resolvedRole1.position === resolvedRole2.position) {
return Number(BigInt(resolvedRole2.id) - BigInt(resolvedRole1.id));

View File

@@ -2,7 +2,7 @@
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, Error, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../errors');
const { StageInstance } = require('../structures/StageInstance');
/**
@@ -57,8 +57,8 @@ class StageInstanceManager extends CachedManager {
*/
async create(channel, options) {
const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new Error(ErrorCodes.StageChannelResolve);
if (typeof options !== 'object') throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve);
if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
let { topic, privacyLevel, sendStartNotification } = options;
const data = await this.client.rest.post(Routes.stageInstances(), {
@@ -86,7 +86,7 @@ class StageInstanceManager extends CachedManager {
*/
async fetch(channel, { cache = true, force = false } = {}) {
const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new Error(ErrorCodes.StageChannelResolve);
if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve);
if (!force) {
const existing = this.cache.find(stageInstance => stageInstance.channelId === channelId);
@@ -116,9 +116,9 @@ class StageInstanceManager extends CachedManager {
* .catch(console.error);
*/
async edit(channel, options) {
if (typeof options !== 'object') throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new Error(ErrorCodes.StageChannelResolve);
if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve);
let { topic, privacyLevel } = options;
@@ -145,7 +145,7 @@ class StageInstanceManager extends CachedManager {
*/
async delete(channel) {
const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new Error(ErrorCodes.StageChannelResolve);
if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve);
await this.client.rest.delete(Routes.stageInstance(channelId));
}

View File

@@ -4,7 +4,7 @@ const { Collection } = require('@discordjs/collection');
const { makeURLSearchParams } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const ThreadChannel = require('../structures/ThreadChannel');
/**
@@ -162,7 +162,7 @@ class ThreadManager extends CachedManager {
query.set('before', timestamp);
}
} catch {
throw new TypeError(ErrorCodes.InvalidType, 'before', 'DateResolvable or ThreadChannelResolvable');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'before', 'DateResolvable or ThreadChannelResolvable');
}
}
}

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const ThreadMember = require('../structures/ThreadMember');
/**
@@ -95,7 +95,7 @@ class ThreadMemberManager extends CachedManager {
*/
async add(member, reason) {
const id = member === '@me' ? member : this.client.users.resolveId(member);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'member', 'UserResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'member', 'UserResolvable');
await this.client.rest.put(Routes.threadMembers(this.thread.id, id), { reason });
return id;
}

View File

@@ -2,7 +2,7 @@
const { ChannelType, Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const { GuildMember } = require('../structures/GuildMember');
const { Message } = require('../structures/Message');
const ThreadMember = require('../structures/ThreadMember');
@@ -69,7 +69,7 @@ class UserManager extends CachedManager {
async deleteDM(user) {
const id = this.resolveId(user);
const dmChannel = this.dmChannel(id);
if (!dmChannel) throw new Error(ErrorCodes.UserNoDMChannel);
if (!dmChannel) throw new DiscordjsError(ErrorCodes.UserNoDMChannel);
await this.client.rest.delete(Routes.channel(dmChannel.id));
this.client.channels._remove(dmChannel.id);
return dmChannel;

View File

@@ -5,7 +5,7 @@ const path = require('node:path');
const process = require('node:process');
const { setTimeout, clearTimeout } = require('node:timers');
const { setTimeout: sleep } = require('node:timers/promises');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const ShardEvents = require('../util/ShardEvents');
const { makeError, makePlainError } = require('../util/Util');
let childProcess = null;
@@ -107,8 +107,8 @@ class Shard extends EventEmitter {
* @returns {Promise<ChildProcess>}
*/
spawn(timeout = 30_000) {
if (this.process) throw new Error(ErrorCodes.ShardingProcessExists, this.id);
if (this.worker) throw new Error(ErrorCodes.ShardingWorkerExists, this.id);
if (this.process) throw new DiscordjsError(ErrorCodes.ShardingProcessExists, this.id);
if (this.worker) throw new DiscordjsError(ErrorCodes.ShardingWorkerExists, this.id);
this._exitListener = this._handleExit.bind(this, undefined, timeout);
@@ -154,17 +154,17 @@ class Shard extends EventEmitter {
const onDisconnect = () => {
cleanup();
reject(new Error(ErrorCodes.ShardingReadyDisconnected, this.id));
reject(new DiscordjsError(ErrorCodes.ShardingReadyDisconnected, this.id));
};
const onDeath = () => {
cleanup();
reject(new Error(ErrorCodes.ShardingReadyDied, this.id));
reject(new DiscordjsError(ErrorCodes.ShardingReadyDied, this.id));
};
const onTimeout = () => {
cleanup();
reject(new Error(ErrorCodes.ShardingReadyTimeout, this.id));
reject(new DiscordjsError(ErrorCodes.ShardingReadyTimeout, this.id));
};
const spawnTimeoutTimer = setTimeout(onTimeout, timeout);
@@ -239,7 +239,9 @@ class Shard extends EventEmitter {
*/
fetchClientValue(prop) {
// Shard is dead (maybe respawning), don't cache anything and error immediately
if (!this.process && !this.worker) return Promise.reject(new Error(ErrorCodes.ShardingNoChildExists, this.id));
if (!this.process && !this.worker) {
return Promise.reject(new DiscordjsError(ErrorCodes.ShardingNoChildExists, this.id));
}
// Cached promise from previous call
if (this._fetches.has(prop)) return this._fetches.get(prop);
@@ -282,7 +284,9 @@ class Shard extends EventEmitter {
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 Error(ErrorCodes.ShardingNoChildExists, this.id));
if (!this.process && !this.worker) {
return Promise.reject(new DiscordjsError(ErrorCodes.ShardingNoChildExists, this.id));
}
// Cached promise from previous call
if (this._evals.has(_eval)) return this._evals.get(_eval);

View File

@@ -1,7 +1,7 @@
'use strict';
const process = require('node:process');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
const Events = require('../util/Events');
const { makeError, makePlainError } = require('../util/Util');
@@ -141,7 +141,7 @@ class ShardClientUtil {
return new Promise((resolve, reject) => {
const parent = this.parentPort ?? process;
if (typeof script !== 'function') {
reject(new TypeError(ErrorCodes.ShardingInvalidEvalBroadcast));
reject(new DiscordjsTypeError(ErrorCodes.ShardingInvalidEvalBroadcast));
return;
}
script = `(${script})(this, ${JSON.stringify(options.context)})`;
@@ -206,7 +206,7 @@ class ShardClientUtil {
*/
_respond(type, message) {
this.send(message).catch(err => {
const error = new globalThis.Error(`Error when sending ${type} response to master process: ${err.message}`);
const error = new Error(`Error when sending ${type} response to master process: ${err.message}`);
error.stack = err.stack;
/**
* Emitted when the client encounters an error.
@@ -246,7 +246,7 @@ class ShardClientUtil {
*/
static shardIdForGuildId(guildId, shardCount) {
const shard = Number(BigInt(guildId) >> 22n) % shardCount;
if (shard < 0) throw new Error(ErrorCodes.ShardingShardMiscalculation, shard, guildId, shardCount);
if (shard < 0) throw new DiscordjsError(ErrorCodes.ShardingShardMiscalculation, shard, guildId, shardCount);
return shard;
}

View File

@@ -7,7 +7,7 @@ const process = require('node:process');
const { setTimeout: sleep } = require('node:timers/promises');
const { Collection } = require('@discordjs/collection');
const Shard = require('./Shard');
const { Error, TypeError, RangeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, DiscordjsRangeError, ErrorCodes } = require('../errors');
const { mergeDefault, fetchRecommendedShardCount } = require('../util/Util');
/**
@@ -64,10 +64,10 @@ class ShardingManager extends EventEmitter {
* @type {string}
*/
this.file = file;
if (!file) throw new Error(ErrorCodes.ClientInvalidOption, 'File', 'specified.');
if (!file) throw new DiscordjsError(ErrorCodes.ClientInvalidOption, 'File', 'specified.');
if (!path.isAbsolute(file)) this.file = path.resolve(process.cwd(), file);
const stats = fs.statSync(this.file);
if (!stats.isFile()) throw new Error(ErrorCodes.ClientInvalidOption, 'File', 'a file');
if (!stats.isFile()) throw new DiscordjsError(ErrorCodes.ClientInvalidOption, 'File', 'a file');
/**
* List of shards this sharding manager spawns
@@ -76,18 +76,18 @@ class ShardingManager extends EventEmitter {
this.shardList = options.shardList ?? 'auto';
if (this.shardList !== 'auto') {
if (!Array.isArray(this.shardList)) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'shardList', 'an array.');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'shardList', 'an array.');
}
this.shardList = [...new Set(this.shardList)];
if (this.shardList.length < 1) {
throw new RangeError(ErrorCodes.ClientInvalidOption, 'shardList', 'at least 1 id.');
throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'shardList', 'at least 1 id.');
}
if (
this.shardList.some(
shardId => typeof shardId !== 'number' || isNaN(shardId) || !Number.isInteger(shardId) || shardId < 0,
)
) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'shardList', 'an array of positive integers.');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'shardList', 'an array of positive integers.');
}
}
@@ -98,13 +98,13 @@ class ShardingManager extends EventEmitter {
this.totalShards = options.totalShards || 'auto';
if (this.totalShards !== 'auto') {
if (typeof this.totalShards !== 'number' || isNaN(this.totalShards)) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'a number.');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'a number.');
}
if (this.totalShards < 1) {
throw new RangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'at least 1.');
throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'at least 1.');
}
if (!Number.isInteger(this.totalShards)) {
throw new RangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'an integer.');
throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'an integer.');
}
}
@@ -114,7 +114,7 @@ class ShardingManager extends EventEmitter {
*/
this.mode = options.mode;
if (this.mode !== 'process' && this.mode !== 'worker') {
throw new RangeError(ErrorCodes.ClientInvalidOption, 'Sharding mode', '"process" or "worker"');
throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Sharding mode', '"process" or "worker"');
}
/**
@@ -190,16 +190,16 @@ class ShardingManager extends EventEmitter {
amount = await fetchRecommendedShardCount(this.token);
} else {
if (typeof amount !== 'number' || isNaN(amount)) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'a number.');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'a number.');
}
if (amount < 1) throw new RangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'at least 1.');
if (amount < 1) throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'at least 1.');
if (!Number.isInteger(amount)) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'an integer.');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'an integer.');
}
}
// Make sure this many shards haven't already been spawned
if (this.shards.size >= amount) throw new Error(ErrorCodes.ShardingAlreadySpawned, this.shards.size);
if (this.shards.size >= amount) throw new DiscordjsError(ErrorCodes.ShardingAlreadySpawned, this.shards.size);
if (this.shardList === 'auto' || this.totalShards === 'auto' || this.totalShards !== amount) {
this.shardList = [...Array(amount).keys()];
}
@@ -208,7 +208,7 @@ class ShardingManager extends EventEmitter {
}
if (this.shardList.some(shardId => shardId >= amount)) {
throw new RangeError(
throw new DiscordjsRangeError(
ErrorCodes.ClientInvalidOption,
'Amount of shards',
'bigger than the highest shardId in the shardList option.',
@@ -252,7 +252,9 @@ class ShardingManager extends EventEmitter {
* @returns {Promise<*|Array<*>>} Results of the script execution
*/
broadcastEval(script, options = {}) {
if (typeof script !== 'function') return Promise.reject(new TypeError(ErrorCodes.ShardingInvalidEvalBroadcast));
if (typeof script !== 'function') {
return Promise.reject(new DiscordjsTypeError(ErrorCodes.ShardingInvalidEvalBroadcast));
}
return this._performOnShards('eval', [`(${script})(this, ${JSON.stringify(options.context)})`], options.shard);
}
@@ -279,14 +281,16 @@ class ShardingManager extends EventEmitter {
* @private
*/
_performOnShards(method, args, shard) {
if (this.shards.size === 0) return Promise.reject(new Error(ErrorCodes.ShardingNoShards));
if (this.shards.size === 0) return Promise.reject(new DiscordjsError(ErrorCodes.ShardingNoShards));
if (typeof shard === 'number') {
if (this.shards.has(shard)) return this.shards.get(shard)[method](...args);
return Promise.reject(new Error(ErrorCodes.ShardingShardNotFound, shard));
return Promise.reject(new DiscordjsError(ErrorCodes.ShardingShardNotFound, shard));
}
if (this.shards.size !== this.shardList.length) return Promise.reject(new Error(ErrorCodes.ShardingInProcess));
if (this.shards.size !== this.shardList.length) {
return Promise.reject(new DiscordjsError(ErrorCodes.ShardingInProcess));
}
const promises = [];
for (const sh of this.shards.values()) promises.push(sh[method](...args));

View File

@@ -3,7 +3,7 @@
const { InteractionResponseType, Routes } = require('discord-api-types/v10');
const BaseInteraction = require('./BaseInteraction');
const CommandInteractionOptionResolver = require('./CommandInteractionOptionResolver');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Represents an autocomplete interaction.
@@ -81,7 +81,7 @@ class AutocompleteInteraction extends BaseInteraction {
* .catch(console.error);
*/
async respond(options) {
if (this.responded) throw new Error(ErrorCodes.InteractionAlreadyReplied);
if (this.responded) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: {

View File

@@ -2,7 +2,7 @@
const { GatewayOpcodes } = require('discord-api-types/v10');
const { Presence } = require('./Presence');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* Represents the client's presence.
@@ -49,7 +49,7 @@ class ClientPresence extends Presence {
if (activities?.length) {
for (const [i, activity] of activities.entries()) {
if (typeof activity.name !== 'string') {
throw new TypeError(ErrorCodes.InvalidType, `activities[${i}].name`, 'string');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, `activities[${i}].name`, 'string');
}
activity.type ??= 0;

View File

@@ -1,7 +1,7 @@
'use strict';
const { ApplicationCommandOptionType } = require('discord-api-types/v10');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* A resolver for command interaction options.
@@ -75,7 +75,7 @@ class CommandInteractionOptionResolver {
const option = this._hoistedOptions.find(opt => opt.name === name);
if (!option) {
if (required) {
throw new TypeError(ErrorCodes.CommandInteractionOptionNotFound, name);
throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionNotFound, name);
}
return null;
}
@@ -96,9 +96,9 @@ class CommandInteractionOptionResolver {
if (!option) {
return null;
} else if (option.type !== type) {
throw new TypeError(ErrorCodes.CommandInteractionOptionType, name, option.type, type);
throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionType, name, option.type, type);
} else if (required && properties.every(prop => option[prop] === null || typeof option[prop] === 'undefined')) {
throw new TypeError(ErrorCodes.CommandInteractionOptionEmpty, name, option.type);
throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionEmpty, name, option.type);
}
return option;
}
@@ -110,7 +110,7 @@ class CommandInteractionOptionResolver {
*/
getSubcommand(required = true) {
if (required && !this._subcommand) {
throw new TypeError(ErrorCodes.CommandInteractionOptionNoSubcommand);
throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionNoSubcommand);
}
return this._subcommand;
}
@@ -122,7 +122,7 @@ class CommandInteractionOptionResolver {
*/
getSubcommandGroup(required = false) {
if (required && !this._group) {
throw new TypeError(ErrorCodes.CommandInteractionOptionNoSubcommandGroup);
throw new DiscordjsTypeError(ErrorCodes.CommandInteractionOptionNoSubcommandGroup);
}
return this._group;
}
@@ -273,7 +273,7 @@ class CommandInteractionOptionResolver {
*/
getFocused(getFull = false) {
const focusedOption = this._hoistedOptions.find(option => option.focused);
if (!focusedOption) throw new TypeError(ErrorCodes.AutocompleteInteractionOptionNoFocusedOption);
if (!focusedOption) throw new DiscordjsTypeError(ErrorCodes.AutocompleteInteractionOptionNoFocusedOption);
return getFull ? focusedOption : focusedOption.value;
}
}

View File

@@ -11,7 +11,7 @@ const GuildTemplate = require('./GuildTemplate');
const Integration = require('./Integration');
const Webhook = require('./Webhook');
const WelcomeScreen = require('./WelcomeScreen');
const { Error, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
const GuildApplicationCommandManager = require('../managers/GuildApplicationCommandManager');
const GuildBanManager = require('../managers/GuildBanManager');
const GuildChannelManager = require('../managers/GuildChannelManager');
@@ -467,7 +467,7 @@ class Guild extends AnonymousGuild {
*/
async fetchOwner(options) {
if (!this.ownerId) {
throw new Error(ErrorCodes.FetchOwnerId);
throw new DiscordjsError(ErrorCodes.FetchOwnerId);
}
const member = await this.members.fetch({ ...options, user: this.ownerId });
return member;
@@ -618,7 +618,7 @@ class Guild extends AnonymousGuild {
*/
async fetchVanityData() {
if (!this.features.includes(GuildFeature.VanityURL)) {
throw new Error(ErrorCodes.VanityURL);
throw new DiscordjsError(ErrorCodes.VanityURL);
}
const data = await this.client.rest.get(Routes.guildVanityUrl(this.id));
this.vanityURLCode = data.code;
@@ -720,7 +720,7 @@ class Guild extends AnonymousGuild {
if (options.user) {
const id = this.client.users.resolveId(options.user);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable');
query.set('user_id', id);
}
@@ -1178,7 +1178,7 @@ class Guild extends AnonymousGuild {
* .catch(console.error);
*/
async leave() {
if (this.ownerId === this.client.user.id) throw new Error(ErrorCodes.GuildOwned);
if (this.ownerId === this.client.user.id) throw new DiscordjsError(ErrorCodes.GuildOwned);
await this.client.rest.delete(Routes.userGuild(this.id));
return this;
}

View File

@@ -2,7 +2,7 @@
const { PermissionFlagsBits } = require('discord-api-types/v10');
const { BaseChannel } = require('./BaseChannel');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const PermissionOverwriteManager = require('../managers/PermissionOverwriteManager');
const { VoiceBasedChannelTypes } = require('../util/Constants');
const PermissionsBitField = require('../util/PermissionsBitField');
@@ -250,7 +250,7 @@ class GuildChannel extends BaseChannel {
* @returns {Promise<GuildChannel>}
*/
lockPermissions() {
if (!this.parent) return Promise.reject(new Error(ErrorCodes.GuildChannelOrphan));
if (!this.parent) return Promise.reject(new DiscordjsError(ErrorCodes.GuildChannelOrphan));
const permissionOverwrites = this.parent.permissionOverwrites.cache.map(overwrite => overwrite.toJSON());
return this.edit({ permissionOverwrites });
}

View File

@@ -2,7 +2,7 @@
const { PermissionFlagsBits } = require('discord-api-types/v10');
const BaseGuildEmoji = require('./BaseGuildEmoji');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const GuildEmojiRoleManager = require('../managers/GuildEmojiRoleManager');
/**
@@ -55,7 +55,7 @@ class GuildEmoji extends BaseGuildEmoji {
* @readonly
*/
get deletable() {
if (!this.guild.members.me) throw new Error(ErrorCodes.GuildUncachedMe);
if (!this.guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe);
return !this.managed && this.guild.members.me.permissions.has(PermissionFlagsBits.ManageEmojisAndStickers);
}

View File

@@ -4,7 +4,7 @@ const { PermissionFlagsBits } = require('discord-api-types/v10');
const Base = require('./Base');
const VoiceState = require('./VoiceState');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const GuildMemberRoleManager = require('../managers/GuildMemberRoleManager');
const PermissionsBitField = require('../util/PermissionsBitField');
@@ -248,7 +248,7 @@ class GuildMember extends Base {
if (this.user.id === this.guild.ownerId) return false;
if (this.user.id === this.client.user.id) return false;
if (this.client.user.id === this.guild.ownerId) return true;
if (!this.guild.members.me) throw new Error(ErrorCodes.GuildUncachedMe);
if (!this.guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe);
return this.guild.members.me.roles.highest.comparePositionTo(this.roles.highest) > 0;
}
@@ -258,7 +258,7 @@ class GuildMember extends Base {
* @readonly
*/
get kickable() {
if (!this.guild.members.me) throw new Error(ErrorCodes.GuildUncachedMe);
if (!this.guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe);
return this.manageable && this.guild.members.me.permissions.has(PermissionFlagsBits.KickMembers);
}
@@ -268,7 +268,7 @@ class GuildMember extends Base {
* @readonly
*/
get bannable() {
if (!this.guild.members.me) throw new Error(ErrorCodes.GuildUncachedMe);
if (!this.guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe);
return this.manageable && this.guild.members.me.permissions.has(PermissionFlagsBits.BanMembers);
}
@@ -301,7 +301,7 @@ class GuildMember extends Base {
*/
permissionsIn(channel) {
channel = this.guild.channels.resolve(channel);
if (!channel) throw new Error(ErrorCodes.GuildChannelResolve);
if (!channel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
return channel.permissionsFor(this);
}

View File

@@ -3,7 +3,7 @@
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { GuildScheduledEventStatus, GuildScheduledEventEntityType, RouteBases } = require('discord-api-types/v10');
const Base = require('./Base');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Represents a scheduled event in a {@link Guild}.
@@ -254,9 +254,9 @@ class GuildScheduledEvent extends Base {
async createInviteURL(options) {
let channelId = this.channelId;
if (this.entityType === GuildScheduledEventEntityType.External) {
if (!options?.channel) throw new Error(ErrorCodes.InviteOptionsMissingChannel);
if (!options?.channel) throw new DiscordjsError(ErrorCodes.InviteOptionsMissingChannel);
channelId = this.guild.channels.resolveId(options.channel);
if (!channelId) throw new Error(ErrorCodes.GuildChannelResolve);
if (!channelId) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
}
const invite = await this.guild.invites.create(channelId, options);
return `${RouteBases.invite}/${invite.code}?event=${this.id}`;

View File

@@ -1,7 +1,7 @@
'use strict';
const { InteractionType } = require('discord-api-types/v10');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Represents an interaction's response
@@ -34,7 +34,7 @@ class InteractionResponse {
collector.once('end', (interactions, reason) => {
const interaction = interactions.first();
if (interaction) resolve(interaction);
else reject(new Error(ErrorCodes.InteractionCollectorError, reason));
else reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason));
});
});
}

View File

@@ -5,7 +5,7 @@ const Base = require('./Base');
const { GuildScheduledEvent } = require('./GuildScheduledEvent');
const IntegrationApplication = require('./IntegrationApplication');
const InviteStageInstance = require('./InviteStageInstance');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Represents an invitation to a guild channel.
@@ -234,7 +234,7 @@ class Invite extends Base {
get deletable() {
const guild = this.guild;
if (!guild || !this.client.guilds.cache.has(guild.id)) return false;
if (!guild.members.me) throw new Error(ErrorCodes.GuildUncachedMe);
if (!guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe);
return Boolean(
this.channel?.permissionsFor(this.client.user).has(PermissionFlagsBits.ManageChannels, false) ||
guild.members.me.permissions.has(PermissionFlagsBits.ManageGuild),

View File

@@ -19,7 +19,7 @@ const Mentions = require('./MessageMentions');
const MessagePayload = require('./MessagePayload');
const ReactionCollector = require('./ReactionCollector');
const { Sticker } = require('./Sticker');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const ReactionManager = require('../managers/ReactionManager');
const { createComponent } = require('../util/Components');
const { NonSystemMessageTypes } = require('../util/Constants');
@@ -565,7 +565,7 @@ class Message extends Base {
collector.once('end', (interactions, reason) => {
const interaction = interactions.first();
if (interaction) resolve(interaction);
else reject(new Error(ErrorCodes.InteractionCollectorError, reason));
else reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason));
});
});
}
@@ -631,10 +631,10 @@ class Message extends Base {
* @returns {Promise<Message>}
*/
async fetchReference() {
if (!this.reference) throw new Error(ErrorCodes.MessageReferenceMissing);
if (!this.reference) throw new DiscordjsError(ErrorCodes.MessageReferenceMissing);
const { channelId, messageId } = this.reference;
const channel = this.client.channels.resolve(channelId);
if (!channel) throw new Error(ErrorCodes.GuildChannelResolve);
if (!channel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
const message = await channel.messages.fetch(messageId);
return message;
}
@@ -669,7 +669,7 @@ class Message extends Base {
* .catch(console.error);
*/
edit(options) {
if (!this.channel) return Promise.reject(new Error(ErrorCodes.ChannelNotCached));
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
return this.channel.messages.edit(this, options);
}
@@ -685,7 +685,7 @@ class Message extends Base {
* }
*/
crosspost() {
if (!this.channel) return Promise.reject(new Error(ErrorCodes.ChannelNotCached));
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
return this.channel.messages.crosspost(this.id);
}
@@ -700,7 +700,7 @@ class Message extends Base {
* .catch(console.error)
*/
async pin(reason) {
if (!this.channel) throw new Error(ErrorCodes.ChannelNotCached);
if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
await this.channel.messages.pin(this.id, reason);
return this;
}
@@ -716,7 +716,7 @@ class Message extends Base {
* .catch(console.error)
*/
async unpin(reason) {
if (!this.channel) throw new Error(ErrorCodes.ChannelNotCached);
if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
await this.channel.messages.unpin(this.id, reason);
return this;
}
@@ -737,7 +737,7 @@ class Message extends Base {
* .catch(console.error);
*/
async react(emoji) {
if (!this.channel) throw new Error(ErrorCodes.ChannelNotCached);
if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
await this.channel.messages.react(this.id, emoji);
return this.client.actions.MessageReactionAdd.handle(
@@ -761,7 +761,7 @@ class Message extends Base {
* .catch(console.error);
*/
async delete() {
if (!this.channel) throw new Error(ErrorCodes.ChannelNotCached);
if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached);
await this.channel.messages.delete(this.id);
return this;
}
@@ -786,7 +786,7 @@ class Message extends Base {
* .catch(console.error);
*/
reply(options) {
if (!this.channel) return Promise.reject(new Error(ErrorCodes.ChannelNotCached));
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
let data;
if (options instanceof MessagePayload) {
@@ -819,11 +819,11 @@ class Message extends Base {
* @returns {Promise<ThreadChannel>}
*/
startThread(options = {}) {
if (!this.channel) return Promise.reject(new Error(ErrorCodes.ChannelNotCached));
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
if (![ChannelType.GuildText, ChannelType.GuildAnnouncement].includes(this.channel.type)) {
return Promise.reject(new Error(ErrorCodes.MessageThreadParent));
return Promise.reject(new DiscordjsError(ErrorCodes.MessageThreadParent));
}
if (this.hasThread) return Promise.reject(new Error(ErrorCodes.MessageExistingThread));
if (this.hasThread) return Promise.reject(new DiscordjsError(ErrorCodes.MessageExistingThread));
return this.channel.threads.create({ ...options, startMessage: this });
}
@@ -833,7 +833,7 @@ class Message extends Base {
* @returns {Promise<Message>}
*/
fetch(force = true) {
if (!this.channel) return Promise.reject(new Error(ErrorCodes.ChannelNotCached));
if (!this.channel) return Promise.reject(new DiscordjsError(ErrorCodes.ChannelNotCached));
return this.channel.messages.fetch({ message: this.id, force });
}
@@ -842,8 +842,8 @@ class Message extends Base {
* @returns {Promise<?Webhook>}
*/
fetchWebhook() {
if (!this.webhookId) return Promise.reject(new Error(ErrorCodes.WebhookMessage));
if (this.webhookId === this.applicationId) return Promise.reject(new Error(ErrorCodes.WebhookApplication));
if (!this.webhookId) return Promise.reject(new DiscordjsError(ErrorCodes.WebhookMessage));
if (this.webhookId === this.applicationId) return Promise.reject(new DiscordjsError(ErrorCodes.WebhookApplication));
return this.client.fetchWebhook(this.webhookId);
}

View File

@@ -5,7 +5,7 @@ const { isJSONEncodable } = require('@discordjs/builders');
const { lazy } = require('@discordjs/util');
const { MessageFlags } = require('discord-api-types/v10');
const ActionRowBuilder = require('./ActionRowBuilder');
const { RangeError, ErrorCodes } = require('../errors');
const { DiscordjsRangeError, ErrorCodes } = require('../errors');
const DataResolver = require('../util/DataResolver');
const MessageFlagsBitField = require('../util/MessageFlagsBitField');
const { basename, verifyString } = require('../util/Util');
@@ -108,7 +108,7 @@ class MessagePayload {
if (this.options.content === null) {
content = '';
} else if (typeof this.options.content !== 'undefined') {
content = verifyString(this.options.content, RangeError, ErrorCodes.MessageContentType, true);
content = verifyString(this.options.content, DiscordjsRangeError, ErrorCodes.MessageContentType, true);
}
return content;
@@ -130,7 +130,7 @@ class MessagePayload {
if (typeof this.options.nonce !== 'undefined') {
nonce = this.options.nonce;
if (typeof nonce === 'number' ? !Number.isInteger(nonce) : typeof nonce !== 'string') {
throw new RangeError(ErrorCodes.MessageNonceType);
throw new DiscordjsRangeError(ErrorCodes.MessageNonceType);
}
}

View File

@@ -2,7 +2,7 @@
const { Collection } = require('@discordjs/collection');
const { ComponentType } = require('discord-api-types/v10');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* Represents the serialized fields from a modal submit interaction
@@ -33,10 +33,10 @@ class ModalSubmitFields {
*/
getField(customId, type) {
const field = this.fields.get(customId);
if (!field) throw new TypeError(ErrorCodes.ModalSubmitInteractionFieldNotFound, customId);
if (!field) throw new DiscordjsTypeError(ErrorCodes.ModalSubmitInteractionFieldNotFound, customId);
if (type !== undefined && type !== field.type) {
throw new TypeError(ErrorCodes.ModalSubmitInteractionFieldType, customId, field.type, type);
throw new DiscordjsTypeError(ErrorCodes.ModalSubmitInteractionFieldType, customId, field.type, type);
}
return field;

View File

@@ -2,7 +2,7 @@
const { Routes } = require('discord-api-types/v10');
const BaseGuildTextChannel = require('./BaseGuildTextChannel');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Represents a guild news channel on Discord.
@@ -23,7 +23,7 @@ class NewsChannel extends BaseGuildTextChannel {
*/
async addFollower(channel, reason) {
const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new Error(ErrorCodes.GuildChannelResolve);
if (!channelId) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
await this.client.rest.post(Routes.channelFollowers(this.id), { body: { webhook_channel_id: channelId }, reason });
return this;
}

View File

@@ -1,7 +1,7 @@
'use strict';
const { BaseChannel } = require('./BaseChannel');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Represents a Partial Group DM Channel on Discord.
@@ -49,11 +49,11 @@ class PartialGroupDMChannel extends BaseChannel {
}
delete() {
return Promise.reject(new Error(ErrorCodes.DeleteGroupDMChannel));
return Promise.reject(new DiscordjsError(ErrorCodes.DeleteGroupDMChannel));
}
fetch() {
return Promise.reject(new Error(ErrorCodes.FetchGroupDMChannel));
return Promise.reject(new DiscordjsError(ErrorCodes.FetchGroupDMChannel));
}
}

View File

@@ -3,7 +3,7 @@
const { OverwriteType } = require('discord-api-types/v10');
const Base = require('./Base');
const { Role } = require('./Role');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const PermissionsBitField = require('../util/PermissionsBitField');
/**
@@ -181,7 +181,7 @@ class PermissionOverwrites extends Base {
}
const userOrRole = guild.roles.resolve(overwrite.id) ?? guild.client.users.resolve(overwrite.id);
if (!userOrRole) throw new TypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
if (!userOrRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
const type = userOrRole instanceof Role ? OverwriteType.Role : OverwriteType.Member;
return {

View File

@@ -3,7 +3,7 @@
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { PermissionFlagsBits } = require('discord-api-types/v10');
const Base = require('./Base');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const PermissionsBitField = require('../util/PermissionsBitField');
/**
@@ -229,7 +229,7 @@ class Role extends Base {
*/
permissionsIn(channel, checkAdmin = true) {
channel = this.guild.channels.resolve(channel);
if (!channel) throw new Error(ErrorCodes.GuildChannelResolve);
if (!channel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
return channel.rolePermissions(this, checkAdmin);
}

View File

@@ -3,7 +3,7 @@
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { Routes, StickerFormatType } = require('discord-api-types/v10');
const Base = require('./Base');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
/**
* Represents a Sticker.
@@ -191,7 +191,7 @@ class Sticker extends Base {
*/
async fetchUser() {
if (this.partial) await this.fetch();
if (!this.guildId) throw new Error(ErrorCodes.NotGuildSticker);
if (!this.guildId) throw new DiscordjsError(ErrorCodes.NotGuildSticker);
return this.guild.stickers.fetchUser(this);
}

View File

@@ -3,7 +3,7 @@
const { ChannelType, PermissionFlagsBits, Routes } = require('discord-api-types/v10');
const { BaseChannel } = require('./BaseChannel');
const TextBasedChannel = require('./interfaces/TextBasedChannel');
const { RangeError, ErrorCodes } = require('../errors');
const { DiscordjsRangeError, ErrorCodes } = require('../errors');
const MessageManager = require('../managers/MessageManager');
const ThreadMemberManager = require('../managers/ThreadMemberManager');
const ChannelFlagsBitField = require('../util/ChannelFlagsBitField');
@@ -400,7 +400,7 @@ class ThreadChannel extends BaseChannel {
*/
setInvitable(invitable = true, reason) {
if (this.type !== ChannelType.PrivateThread) {
return Promise.reject(new RangeError(ErrorCodes.ThreadInvitableType, this.type));
return Promise.reject(new DiscordjsRangeError(ErrorCodes.ThreadInvitableType, this.type));
}
return this.edit({ invitable, reason });
}

View File

@@ -2,7 +2,7 @@
const { ChannelType, Routes } = require('discord-api-types/v10');
const Base = require('./Base');
const { Error, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* Represents the voice state for a Guild Member.
@@ -220,20 +220,20 @@ class VoiceState extends Base {
* @returns {Promise<VoiceState>}
*/
async edit(data) {
if (this.channel?.type !== ChannelType.GuildStageVoice) throw new Error(ErrorCodes.VoiceNotStageChannel);
if (this.channel?.type !== ChannelType.GuildStageVoice) throw new DiscordjsError(ErrorCodes.VoiceNotStageChannel);
const target = this.client.user.id === this.id ? '@me' : this.id;
if (target !== '@me' && typeof data.requestToSpeak !== 'undefined') {
throw new Error(ErrorCodes.VoiceStateNotOwn);
throw new DiscordjsError(ErrorCodes.VoiceStateNotOwn);
}
if (!['boolean', 'undefined'].includes(typeof data.requestToSpeak)) {
throw new TypeError(ErrorCodes.VoiceStateInvalidType, 'requestToSpeak');
throw new DiscordjsTypeError(ErrorCodes.VoiceStateInvalidType, 'requestToSpeak');
}
if (!['boolean', 'undefined'].includes(typeof data.suppressed)) {
throw new TypeError(ErrorCodes.VoiceStateInvalidType, 'suppressed');
throw new DiscordjsTypeError(ErrorCodes.VoiceStateInvalidType, 'suppressed');
}
await this.client.rest.patch(Routes.guildVoiceState(this.guild.id, target), {

View File

@@ -5,7 +5,7 @@ const { lazy } = require('@discordjs/util');
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { Routes, WebhookType } = require('discord-api-types/v10');
const MessagePayload = require('./MessagePayload');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const DataResolver = require('../util/DataResolver');
const getMessage = lazy(() => require('./Message').Message);
@@ -190,7 +190,7 @@ class Webhook {
* .catch(console.error);
*/
async send(options) {
if (!this.token) throw new Error(ErrorCodes.WebhookTokenUnavailable);
if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable);
let messagePayload;
@@ -231,7 +231,7 @@ class Webhook {
* @see {@link https://api.slack.com/messaging/webhooks}
*/
async sendSlackMessage(body) {
if (!this.token) throw new Error(ErrorCodes.WebhookTokenUnavailable);
if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable);
const data = await this.client.rest.post(Routes.webhookPlatform(this.id, this.token, 'slack'), {
query: makeURLSearchParams({ wait: true }),
@@ -287,7 +287,7 @@ class Webhook {
* @returns {Promise<Message>} Returns the message sent by this webhook
*/
async fetchMessage(message, { threadId } = {}) {
if (!this.token) throw new Error(ErrorCodes.WebhookTokenUnavailable);
if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable);
const data = await this.client.rest.get(Routes.webhookMessage(this.id, this.token, message), {
query: threadId ? makeURLSearchParams({ thread_id: threadId }) : undefined,
@@ -308,7 +308,7 @@ class Webhook {
* @returns {Promise<Message>} Returns the message edited by this webhook
*/
async editMessage(message, options) {
if (!this.token) throw new Error(ErrorCodes.WebhookTokenUnavailable);
if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable);
let messagePayload;
@@ -359,7 +359,7 @@ class Webhook {
* @returns {Promise<void>}
*/
async deleteMessage(message, threadId) {
if (!this.token) throw new Error(ErrorCodes.WebhookTokenUnavailable);
if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable);
await this.client.rest.delete(
Routes.webhookMessage(this.id, this.token, typeof message === 'string' ? message : message.id),

View File

@@ -3,7 +3,7 @@
const EventEmitter = require('node:events');
const { setTimeout, clearTimeout } = require('node:timers');
const { Collection } = require('@discordjs/collection');
const { TypeError, ErrorCodes } = require('../../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../../errors');
const { flatten } = require('../../util/Util');
/**
@@ -87,7 +87,7 @@ class Collector extends EventEmitter {
this._endReason = null;
if (typeof this.filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'options.filter', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options.filter', 'function');
}
this.handleCollect = this.handleCollect.bind(this);

View File

@@ -2,7 +2,7 @@
const { isJSONEncodable } = require('@discordjs/builders');
const { InteractionResponseType, MessageFlags, Routes, InteractionType } = require('discord-api-types/v10');
const { Error, ErrorCodes } = require('../../errors');
const { DiscordjsError, ErrorCodes } = require('../../errors');
const InteractionCollector = require('../InteractionCollector');
const InteractionResponse = require('../InteractionResponse');
const MessagePayload = require('../MessagePayload');
@@ -64,7 +64,7 @@ class InteractionResponses {
* .catch(console.error);
*/
async deferReply(options = {}) {
if (this.deferred || this.replied) throw new Error(ErrorCodes.InteractionAlreadyReplied);
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
this.ephemeral = options.ephemeral ?? false;
await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: {
@@ -99,7 +99,7 @@ class InteractionResponses {
* .catch(console.error);
*/
async reply(options) {
if (this.deferred || this.replied) throw new Error(ErrorCodes.InteractionAlreadyReplied);
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
this.ephemeral = options.ephemeral ?? false;
let messagePayload;
@@ -147,7 +147,7 @@ class InteractionResponses {
* .catch(console.error);
*/
async editReply(options) {
if (!this.deferred && !this.replied) throw new Error(ErrorCodes.InteractionNotReplied);
if (!this.deferred && !this.replied) throw new DiscordjsError(ErrorCodes.InteractionNotReplied);
const message = await this.webhook.editMessage('@original', options);
this.replied = true;
return message;
@@ -164,7 +164,7 @@ class InteractionResponses {
* .catch(console.error);
*/
async deleteReply() {
if (this.ephemeral) throw new Error(ErrorCodes.InteractionEphemeralReplied);
if (this.ephemeral) throw new DiscordjsError(ErrorCodes.InteractionEphemeralReplied);
await this.webhook.deleteMessage('@original');
}
@@ -174,7 +174,7 @@ class InteractionResponses {
* @returns {Promise<Message>}
*/
followUp(options) {
if (!this.deferred && !this.replied) return Promise.reject(new Error(ErrorCodes.InteractionNotReplied));
if (!this.deferred && !this.replied) return Promise.reject(new DiscordjsError(ErrorCodes.InteractionNotReplied));
return this.webhook.send(options);
}
@@ -189,7 +189,7 @@ class InteractionResponses {
* .catch(console.error);
*/
async deferUpdate(options = {}) {
if (this.deferred || this.replied) throw new Error(ErrorCodes.InteractionAlreadyReplied);
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: {
type: InteractionResponseType.DeferredMessageUpdate,
@@ -215,7 +215,7 @@ class InteractionResponses {
* .catch(console.error);
*/
async update(options) {
if (this.deferred || this.replied) throw new Error(ErrorCodes.InteractionAlreadyReplied);
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
let messagePayload;
if (options instanceof MessagePayload) messagePayload = options;
@@ -242,7 +242,7 @@ class InteractionResponses {
* @returns {Promise<void>}
*/
async showModal(modal) {
if (this.deferred || this.replied) throw new Error(ErrorCodes.InteractionAlreadyReplied);
if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied);
await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: {
type: InteractionResponseType.Modal,
@@ -272,14 +272,14 @@ class InteractionResponses {
* .catch(console.error);
*/
awaitModalSubmit(options) {
if (typeof options.time !== 'number') throw new Error(ErrorCodes.InvalidType, 'time', 'number');
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) => {
const collector = new InteractionCollector(this.client, _options);
collector.once('end', (interactions, reason) => {
const interaction = interactions.first();
if (interaction) resolve(interaction);
else reject(new Error(ErrorCodes.InteractionCollectorError, reason));
else reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason));
});
});
}

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { DiscordSnowflake } = require('@sapphire/snowflake');
const { InteractionType, Routes } = require('discord-api-types/v10');
const { TypeError, Error, ErrorCodes } = require('../../errors');
const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../../errors');
const InteractionCollector = require('../InteractionCollector');
const MessageCollector = require('../MessageCollector');
const MessagePayload = require('../MessagePayload');
@@ -273,7 +273,7 @@ class TextBasedChannel {
collector.once('end', (interactions, reason) => {
const interaction = interactions.first();
if (interaction) resolve(interaction);
else reject(new Error(ErrorCodes.InteractionCollectorError, reason));
else reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason));
});
});
}
@@ -326,7 +326,7 @@ class TextBasedChannel {
const msgs = await this.messages.fetch({ limit: messages });
return this.bulkDelete(msgs, filterOld);
}
throw new TypeError(ErrorCodes.MessageBulkDeleteType);
throw new DiscordjsTypeError(ErrorCodes.MessageBulkDeleteType);
}
/**

View File

@@ -1,6 +1,6 @@
'use strict';
const { RangeError, ErrorCodes } = require('../errors');
const { DiscordjsRangeError, ErrorCodes } = require('../errors');
/**
* Data structure that makes it easy to interact with a bitfield.
@@ -165,7 +165,7 @@ class BitField {
if (typeof this.Flags[bit] !== 'undefined') return this.Flags[bit];
if (!isNaN(bit)) return typeof DefaultBit === 'bigint' ? BigInt(bit) : Number(bit);
}
throw new RangeError(ErrorCodes.BitFieldInvalid, bit);
throw new DiscordjsRangeError(ErrorCodes.BitFieldInvalid, bit);
}
}

View File

@@ -4,7 +4,7 @@ const { Buffer } = require('node:buffer');
const fs = require('node:fs/promises');
const path = require('node:path');
const { fetch } = require('undici');
const { Error: DiscordError, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
const Invite = require('../structures/Invite');
/**
@@ -129,11 +129,11 @@ class DataResolver extends null {
const file = path.resolve(resource);
const stats = await fs.stat(file);
if (!stats.isFile()) throw new DiscordError(ErrorCodes.FileNotFound, file);
if (!stats.isFile()) throw new DiscordjsError(ErrorCodes.FileNotFound, file);
return { data: await fs.readFile(file) };
}
throw new TypeError(ErrorCodes.ReqResourceType);
throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);
}
}

View File

@@ -1,7 +1,7 @@
'use strict';
const { Collection } = require('@discordjs/collection');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* Options for defining the behavior of a LimitedCollection
@@ -20,15 +20,15 @@ const { TypeError, ErrorCodes } = require('../errors');
class LimitedCollection extends Collection {
constructor(options = {}, iterable) {
if (typeof options !== 'object' || options === null) {
throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
}
const { maxSize = Infinity, keepOverLimit = null } = options;
if (typeof maxSize !== 'number') {
throw new TypeError(ErrorCodes.InvalidType, 'maxSize', 'number');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'maxSize', 'number');
}
if (keepOverLimit !== null && typeof keepOverLimit !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'keepOverLimit', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'keepOverLimit', 'function');
}
super(iterable);

View File

@@ -3,7 +3,7 @@
const { setInterval, clearInterval } = require('node:timers');
const { ThreadChannelTypes, SweeperKeys } = require('./Constants');
const Events = require('./Events');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
/**
* @typedef {Function} GlobalSweepFilter
@@ -131,7 +131,7 @@ class Sweepers {
*/
sweepMessages(filter) {
if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
}
let channels = 0;
let messages = 0;
@@ -162,7 +162,7 @@ class Sweepers {
*/
sweepReactions(filter) {
if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
}
let channels = 0;
let messages = 0;
@@ -210,7 +210,7 @@ class Sweepers {
*/
sweepThreadMembers(filter) {
if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
}
let threads = 0;
@@ -240,7 +240,7 @@ class Sweepers {
*/
sweepThreads(filter) {
if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
}
let threads = 0;
@@ -262,7 +262,7 @@ class Sweepers {
*/
sweepUsers(filter) {
if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
}
const users = this.client.users.cache.sweep(filter);
@@ -313,13 +313,13 @@ class Sweepers {
excludeFromSweep = () => false,
} = {}) {
if (typeof lifetime !== 'number') {
throw new TypeError(ErrorCodes.InvalidType, 'lifetime', 'number');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'lifetime', 'number');
}
if (typeof getComparisonTimestamp !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'getComparisonTimestamp', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'getComparisonTimestamp', 'function');
}
if (typeof excludeFromSweep !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'excludeFromSweep', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'excludeFromSweep', 'function');
}
return () => {
if (lifetime <= 0) return null;
@@ -391,7 +391,7 @@ class Sweepers {
*/
_sweepGuildDirectProp(key, filter, { emit = true, outputName } = {}) {
if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
}
let guilds = 0;
@@ -419,20 +419,20 @@ class Sweepers {
_validateProperties(key) {
const props = this.options[key];
if (typeof props !== 'object') {
throw new TypeError(ErrorCodes.InvalidType, `sweepers.${key}`, 'object', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, `sweepers.${key}`, 'object', true);
}
if (typeof props.interval !== 'number') {
throw new TypeError(ErrorCodes.InvalidType, `sweepers.${key}.interval`, 'number');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, `sweepers.${key}.interval`, 'number');
}
// Invites, Messages, and Threads can be provided a lifetime parameter, which we use to generate the filter
if (['invites', 'messages', 'threads'].includes(key) && !('filter' in props)) {
if (typeof props.lifetime !== 'number') {
throw new TypeError(ErrorCodes.InvalidType, `sweepers.${key}.lifetime`, 'number');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, `sweepers.${key}.lifetime`, 'number');
}
return;
}
if (typeof props.filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, `sweepers.${key}.filter`, 'function');
throw new DiscordjsTypeError(ErrorCodes.InvalidType, `sweepers.${key}.filter`, 'function');
}
}
@@ -448,7 +448,7 @@ class Sweepers {
this.intervals[intervalKey] = setInterval(() => {
const sweepFn = opts.filter();
if (sweepFn === null) return;
if (typeof sweepFn !== 'function') throw new TypeError(ErrorCodes.SweepFilterReturn);
if (typeof sweepFn !== 'function') throw new DiscordjsTypeError(ErrorCodes.SweepFilterReturn);
this[sweepKey](sweepFn);
}, opts.interval * 1_000).unref();
}

View File

@@ -5,7 +5,7 @@ const { Collection } = require('@discordjs/collection');
const { ChannelType, RouteBases, Routes } = require('discord-api-types/v10');
const { fetch } = require('undici');
const Colors = require('./Colors');
const { Error: DiscordError, RangeError, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsRangeError, DiscordjsTypeError, ErrorCodes } = require('../errors');
const isObject = d => typeof d === 'object' && d !== null;
/**
@@ -223,13 +223,13 @@ function escapeSpoiler(text) {
* @returns {Promise<number>} The recommended number of shards
*/
async function fetchRecommendedShardCount(token, { guildsPerShard = 1_000, multipleOf = 1 } = {}) {
if (!token) throw new DiscordError(ErrorCodes.TokenMissing);
if (!token) throw new DiscordjsError(ErrorCodes.TokenMissing);
const response = await fetch(RouteBases.api + Routes.gatewayBot(), {
method: 'GET',
headers: { Authorization: `Bot ${token.replace(/^Bot\s*/i, '')}` },
});
if (!response.ok) {
if (response.status === 401) throw new DiscordError(ErrorCodes.TokenInvalid);
if (response.status === 401) throw new DiscordjsError(ErrorCodes.TokenInvalid);
throw response;
}
const { shards } = await response.json();
@@ -413,8 +413,8 @@ function resolveColor(color) {
color = (color[0] << 16) + (color[1] << 8) + color[2];
}
if (color < 0 || color > 0xffffff) throw new RangeError(ErrorCodes.ColorRange);
else if (Number.isNaN(color)) throw new TypeError(ErrorCodes.ColorConvert);
if (color < 0 || color > 0xffffff) throw new DiscordjsRangeError(ErrorCodes.ColorRange);
else if (Number.isNaN(color)) throw new DiscordjsTypeError(ErrorCodes.ColorConvert);
return color;
}