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 EventEmitter = require('node:events');
const { REST } = require('@discordjs/rest'); const { REST } = require('@discordjs/rest');
const { TypeError, ErrorCodes } = require('../errors'); const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const Options = require('../util/Options'); const Options = require('../util/Options');
const { mergeDefault, flatten } = require('../util/Util'); const { mergeDefault, flatten } = require('../util/Util');
@@ -15,7 +15,7 @@ class BaseClient extends EventEmitter {
super({ captureRejections: true }); super({ captureRejections: true });
if (typeof options !== 'object' || options === null) { 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 ActionsManager = require('./actions/ActionsManager');
const ClientVoiceManager = require('./voice/ClientVoiceManager'); const ClientVoiceManager = require('./voice/ClientVoiceManager');
const WebSocketManager = require('./websocket/WebSocketManager'); 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 BaseGuildEmojiManager = require('../managers/BaseGuildEmojiManager');
const ChannelManager = require('../managers/ChannelManager'); const ChannelManager = require('../managers/ChannelManager');
const GuildManager = require('../managers/GuildManager'); const GuildManager = require('../managers/GuildManager');
@@ -211,7 +211,7 @@ class Client extends BaseClient {
* client.login('my token'); * client.login('my token');
*/ */
async login(token = this.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.token = token = token.replace(/^(Bot|Bearer)\s*/i, '');
this.rest.setToken(token); this.rest.setToken(token);
this.emit( this.emit(
@@ -366,7 +366,7 @@ class Client extends BaseClient {
*/ */
async fetchGuildPreview(guild) { async fetchGuildPreview(guild) {
const id = this.guilds.resolveId(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)); const data = await this.rest.get(Routes.guildPreview(id));
return new GuildPreview(this, data); return new GuildPreview(this, data);
} }
@@ -378,7 +378,7 @@ class Client extends BaseClient {
*/ */
async fetchGuildWidget(guild) { async fetchGuildWidget(guild) {
const id = this.guilds.resolveId(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)); const data = await this.rest.get(Routes.guildWidgetJSON(id));
return new Widget(this, data); return new Widget(this, data);
} }
@@ -413,23 +413,23 @@ class Client extends BaseClient {
* console.log(`Generated bot invite link: ${link}`); * console.log(`Generated bot invite link: ${link}`);
*/ */
generateInvite(options = {}) { generateInvite(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);
if (!this.application) throw new Error(ErrorCodes.ClientNotReady, 'generate an invite link'); if (!this.application) throw new DiscordjsError(ErrorCodes.ClientNotReady, 'generate an invite link');
const { scopes } = options; const { scopes } = options;
if (typeof scopes === 'undefined') { if (typeof scopes === 'undefined') {
throw new TypeError(ErrorCodes.InvalidMissingScopes); throw new DiscordjsTypeError(ErrorCodes.InvalidMissingScopes);
} }
if (!Array.isArray(scopes)) { 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))) { 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 validScopes = Object.values(OAuth2Scopes);
const invalidScope = scopes.find(scope => !validScopes.includes(scope)); const invalidScope = scopes.find(scope => !validScopes.includes(scope));
if (invalidScope) { if (invalidScope) {
throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'scopes', invalidScope); throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'scopes', invalidScope);
} }
const query = makeURLSearchParams({ const query = makeURLSearchParams({
@@ -445,7 +445,7 @@ class Client extends BaseClient {
if (options.guild) { if (options.guild) {
const guildId = this.guilds.resolveId(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); query.set('guild_id', guildId);
} }
@@ -477,31 +477,31 @@ class Client extends BaseClient {
*/ */
_validateOptions(options = this.options) { _validateOptions(options = this.options) {
if (typeof options.intents === 'undefined') { if (typeof options.intents === 'undefined') {
throw new TypeError(ErrorCodes.ClientMissingIntents); throw new DiscordjsTypeError(ErrorCodes.ClientMissingIntents);
} else { } else {
options.intents = IntentsBitField.resolve(options.intents); options.intents = IntentsBitField.resolve(options.intents);
} }
if (typeof options.shardCount !== 'number' || isNaN(options.shardCount) || options.shardCount < 1) { 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))) { 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') { 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) { 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)) { 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)) { 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') { 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'; 'use strict';
const BaseClient = require('./BaseClient'); const BaseClient = require('./BaseClient');
const { Error, ErrorCodes } = require('../errors'); const { DiscordjsError, ErrorCodes } = require('../errors');
const Webhook = require('../structures/Webhook'); const Webhook = require('../structures/Webhook');
const { parseWebhookURL } = require('../util/Util'); const { parseWebhookURL } = require('../util/Util');
@@ -48,7 +48,7 @@ class WebhookClient extends BaseClient {
if ('url' in data) { if ('url' in data) {
const parsed = parseWebhookURL(data.url); const parsed = parseWebhookURL(data.url);
if (!parsed) { if (!parsed) {
throw new Error(ErrorCodes.WebhookURLInvalid); throw new DiscordjsError(ErrorCodes.WebhookURLInvalid);
} }
({ id, token } = parsed); ({ id, token } = parsed);

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,7 @@
'use strict'; 'use strict';
const BaseManager = require('./BaseManager'); 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. * Manages the API methods of a data model along with a collection of instances.
@@ -28,7 +28,7 @@ class DataManager extends BaseManager {
* @abstract * @abstract
*/ */
get cache() { 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 { makeURLSearchParams } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10'); const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager'); const CachedManager = require('./CachedManager');
const { TypeError, Error, ErrorCodes } = require('../errors'); const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../errors');
const GuildBan = require('../structures/GuildBan'); const GuildBan = require('../structures/GuildBan');
const { GuildMember } = require('../structures/GuildMember'); const { GuildMember } = require('../structures/GuildMember');
@@ -104,7 +104,7 @@ class GuildBanManager extends CachedManager {
if (resolvedUser) return this._fetchSingle({ user: resolvedUser, cache, force }); if (resolvedUser) return this._fetchSingle({ user: resolvedUser, cache, force });
if (!before && !after && !limit && typeof cache === 'undefined') { 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); return this._fetchMany(options);
@@ -152,9 +152,9 @@ class GuildBanManager extends CachedManager {
* .catch(console.error); * .catch(console.error);
*/ */
async create(user, options = {}) { 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); 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) { if (typeof options.deleteMessageDays !== 'undefined' && !deprecationEmittedForDeleteMessageDays) {
process.emitWarning( process.emitWarning(
@@ -195,7 +195,7 @@ class GuildBanManager extends CachedManager {
*/ */
async remove(user, reason) { async remove(user, reason) {
const id = this.client.users.resolveId(user); 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 }); await this.client.rest.delete(Routes.guildBan(this.guild.id, id), { reason });
return this.client.users.resolve(user); 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 { ChannelType, Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager'); const CachedManager = require('./CachedManager');
const GuildTextThreadManager = require('./GuildTextThreadManager'); const GuildTextThreadManager = require('./GuildTextThreadManager');
const { Error, TypeError, ErrorCodes } = require('../errors'); const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
const GuildChannel = require('../structures/GuildChannel'); const GuildChannel = require('../structures/GuildChannel');
const PermissionOverwrites = require('../structures/PermissionOverwrites'); const PermissionOverwrites = require('../structures/PermissionOverwrites');
const ThreadChannel = require('../structures/ThreadChannel'); const ThreadChannel = require('../structures/ThreadChannel');
@@ -195,7 +195,7 @@ class GuildChannelManager extends CachedManager {
*/ */
async createWebhook({ channel, name, avatar, reason }) { async createWebhook({ channel, name, avatar, reason }) {
const id = this.resolveId(channel); 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:')) { if (typeof avatar === 'string' && !avatar.startsWith('data:')) {
avatar = await DataResolver.resolveImage(avatar); avatar = await DataResolver.resolveImage(avatar);
} }
@@ -250,7 +250,7 @@ class GuildChannelManager extends CachedManager {
*/ */
async edit(channel, data) { async edit(channel, data) {
channel = this.resolve(channel); 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); const parent = data.parent && this.client.channels.resolveId(data.parent);
@@ -316,7 +316,7 @@ class GuildChannelManager extends CachedManager {
*/ */
async setPosition(channel, position, { relative, reason } = {}) { async setPosition(channel, position, { relative, reason } = {}) {
channel = this.resolve(channel); 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( const updatedChannels = await setPosition(
channel, channel,
position, position,
@@ -359,7 +359,7 @@ class GuildChannelManager extends CachedManager {
if (id) { if (id) {
const data = await this.client.rest.get(Routes.channel(id)); const data = await this.client.rest.get(Routes.channel(id));
// Since this is the guild manager, throw if on a different guild // 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 }); return this.client.channels._add(data, this.guild, { cache });
} }
@@ -381,7 +381,7 @@ class GuildChannelManager extends CachedManager {
*/ */
async fetchWebhooks(channel) { async fetchWebhooks(channel) {
const id = this.resolveId(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)); 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()); 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) { async delete(channel, reason) {
const id = this.resolveId(channel); 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 }); await this.client.rest.delete(Routes.channel(id), { reason });
this.client.actions.ChannelDelete.handle({ id }); this.client.actions.ChannelDelete.handle({ id });
} }

View File

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

View File

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

View File

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

View File

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

View File

@@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection'); const { Collection } = require('@discordjs/collection');
const { Routes } = require('discord-api-types/v10'); const { Routes } = require('discord-api-types/v10');
const DataManager = require('./DataManager'); const DataManager = require('./DataManager');
const { TypeError, ErrorCodes } = require('../errors'); const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const { Role } = require('../structures/Role'); const { Role } = require('../structures/Role');
/** /**
@@ -110,7 +110,9 @@ class GuildMemberRoleManager extends DataManager {
const resolvedRoles = []; const resolvedRoles = [];
for (const role of roleOrRoles.values()) { for (const role of roleOrRoles.values()) {
const resolvedRole = this.guild.roles.resolveId(role); const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) 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); resolvedRoles.push(resolvedRole);
} }
@@ -119,7 +121,7 @@ class GuildMemberRoleManager extends DataManager {
} else { } else {
roleOrRoles = this.guild.roles.resolveId(roleOrRoles); roleOrRoles = this.guild.roles.resolveId(roleOrRoles);
if (roleOrRoles === null) { if (roleOrRoles === null) {
throw new TypeError( throw new DiscordjsTypeError(
ErrorCodes.InvalidType, ErrorCodes.InvalidType,
'roles', 'roles',
'Role, Snowflake or Array or Collection of Roles or Snowflakes', 'Role, Snowflake or Array or Collection of Roles or Snowflakes',
@@ -145,7 +147,9 @@ class GuildMemberRoleManager extends DataManager {
const resolvedRoles = []; const resolvedRoles = [];
for (const role of roleOrRoles.values()) { for (const role of roleOrRoles.values()) {
const resolvedRole = this.guild.roles.resolveId(role); const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) 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); resolvedRoles.push(resolvedRole);
} }
@@ -154,7 +158,7 @@ class GuildMemberRoleManager extends DataManager {
} else { } else {
roleOrRoles = this.guild.roles.resolveId(roleOrRoles); roleOrRoles = this.guild.roles.resolveId(roleOrRoles);
if (roleOrRoles === null) { if (roleOrRoles === null) {
throw new TypeError( throw new DiscordjsTypeError(
ErrorCodes.InvalidType, ErrorCodes.InvalidType,
'roles', 'roles',
'Role, Snowflake or Array or Collection of Roles or Snowflakes', '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 { makeURLSearchParams } = require('@discordjs/rest');
const { GuildScheduledEventEntityType, Routes } = require('discord-api-types/v10'); const { GuildScheduledEventEntityType, Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager'); const CachedManager = require('./CachedManager');
const { TypeError, Error, ErrorCodes } = require('../errors'); const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../errors');
const { GuildScheduledEvent } = require('../structures/GuildScheduledEvent'); const { GuildScheduledEvent } = require('../structures/GuildScheduledEvent');
const DataResolver = require('../util/DataResolver'); const DataResolver = require('../util/DataResolver');
@@ -69,7 +69,7 @@ class GuildScheduledEventManager extends CachedManager {
* @returns {Promise<GuildScheduledEvent>} * @returns {Promise<GuildScheduledEvent>}
*/ */
async create(options) { 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 { let {
privacyLevel, privacyLevel,
entityType, entityType,
@@ -89,7 +89,7 @@ class GuildScheduledEventManager extends CachedManager {
entity_metadata = { location: entityMetadata?.location }; entity_metadata = { location: entityMetadata?.location };
} else { } else {
channel_id = this.guild.channels.resolveId(channel); 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; entity_metadata = typeof entityMetadata === 'undefined' ? entityMetadata : null;
} }
@@ -188,9 +188,9 @@ class GuildScheduledEventManager extends CachedManager {
*/ */
async edit(guildScheduledEvent, options) { async edit(guildScheduledEvent, options) {
const guildScheduledEventId = this.resolveId(guildScheduledEvent); 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 { let {
privacyLevel, privacyLevel,
entityType, entityType,
@@ -238,7 +238,7 @@ class GuildScheduledEventManager extends CachedManager {
*/ */
async delete(guildScheduledEvent) { async delete(guildScheduledEvent) {
const guildScheduledEventId = this.resolveId(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)); await this.client.rest.delete(Routes.guildScheduledEvent(this.guild.id, guildScheduledEventId));
} }
@@ -269,7 +269,7 @@ class GuildScheduledEventManager extends CachedManager {
*/ */
async fetchSubscribers(guildScheduledEvent, options = {}) { async fetchSubscribers(guildScheduledEvent, options = {}) {
const guildScheduledEventId = this.resolveId(guildScheduledEvent); const guildScheduledEventId = this.resolveId(guildScheduledEvent);
if (!guildScheduledEventId) throw new Error(ErrorCodes.GuildScheduledEventResolve); if (!guildScheduledEventId) throw new DiscordjsError(ErrorCodes.GuildScheduledEventResolve);
const query = makeURLSearchParams({ const query = makeURLSearchParams({
limit: options.limit, limit: options.limit,

View File

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

View File

@@ -2,7 +2,7 @@
const { ChannelType, Routes } = require('discord-api-types/v10'); const { ChannelType, Routes } = require('discord-api-types/v10');
const ThreadManager = require('./ThreadManager'); 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. * Manages API methods for {@link ThreadChannel} objects and stores their cache.
@@ -68,7 +68,7 @@ class GuildTextThreadManager extends ThreadManager {
let startMessageId; let startMessageId;
if (startMessage) { if (startMessage) {
startMessageId = this.channel.messages.resolveId(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) { } else if (this.channel.type !== ChannelType.GuildAnnouncement) {
resolvedType = type ?? resolvedType; resolvedType = type ?? resolvedType;
} }

View File

@@ -4,7 +4,7 @@ const { Collection } = require('@discordjs/collection');
const { makeURLSearchParams } = require('@discordjs/rest'); const { makeURLSearchParams } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10'); const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager'); const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors'); const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const { Message } = require('../structures/Message'); const { Message } = require('../structures/Message');
const MessagePayload = require('../structures/MessagePayload'); const MessagePayload = require('../structures/MessagePayload');
const { resolvePartialEmoji } = require('../util/Util'); const { resolvePartialEmoji } = require('../util/Util');
@@ -164,7 +164,7 @@ class MessageManager extends CachedManager {
*/ */
async edit(message, options) { async edit(message, options) {
const messageId = this.resolveId(message); 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 const { body, files } = await (options instanceof MessagePayload
? options ? options
@@ -190,7 +190,7 @@ class MessageManager extends CachedManager {
*/ */
async crosspost(message) { async crosspost(message) {
message = this.resolveId(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)); const data = await this.client.rest.post(Routes.channelMessageCrosspost(this.channel.id, message));
return this.cache.get(data.id) ?? this._add(data); return this.cache.get(data.id) ?? this._add(data);
@@ -204,7 +204,7 @@ class MessageManager extends CachedManager {
*/ */
async pin(message, reason) { async pin(message, reason) {
message = this.resolveId(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.put(Routes.channelPin(this.channel.id, message), { reason }); await this.client.rest.put(Routes.channelPin(this.channel.id, message), { reason });
} }
@@ -217,7 +217,7 @@ class MessageManager extends CachedManager {
*/ */
async unpin(message, reason) { async unpin(message, reason) {
message = this.resolveId(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.channelPin(this.channel.id, message), { reason }); await this.client.rest.delete(Routes.channelPin(this.channel.id, message), { reason });
} }
@@ -230,10 +230,10 @@ class MessageManager extends CachedManager {
*/ */
async react(message, emoji) { async react(message, emoji) {
message = this.resolveId(message); 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); 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 const emojiId = emoji.id
? `${emoji.animated ? 'a:' : ''}${emoji.name}:${emoji.id}` ? `${emoji.animated ? 'a:' : ''}${emoji.name}:${emoji.id}`
@@ -249,7 +249,7 @@ class MessageManager extends CachedManager {
*/ */
async delete(message) { async delete(message) {
message = this.resolveId(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)); 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 { Collection } = require('@discordjs/collection');
const { OverwriteType, Routes } = require('discord-api-types/v10'); const { OverwriteType, Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager'); const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors'); const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const PermissionOverwrites = require('../structures/PermissionOverwrites'); const PermissionOverwrites = require('../structures/PermissionOverwrites');
const { Role } = require('../structures/Role'); const { Role } = require('../structures/Role');
@@ -65,7 +65,12 @@ class PermissionOverwriteManager extends CachedManager {
set(overwrites, reason) { set(overwrites, reason) {
if (!Array.isArray(overwrites) && !(overwrites instanceof Collection)) { if (!Array.isArray(overwrites) && !(overwrites instanceof Collection)) {
return Promise.reject( 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 }); return this.channel.edit({ permissionOverwrites: overwrites, reason });
@@ -93,7 +98,7 @@ class PermissionOverwriteManager extends CachedManager {
let { type, reason } = overwriteOptions; let { type, reason } = overwriteOptions;
if (typeof type !== 'number') { if (typeof type !== 'number') {
userOrRole = this.channel.guild.roles.resolve(userOrRole) ?? this.client.users.resolve(userOrRole); 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; type = userOrRole instanceof Role ? OverwriteType.Role : OverwriteType.Member;
} }
@@ -153,7 +158,7 @@ class PermissionOverwriteManager extends CachedManager {
*/ */
async delete(userOrRole, reason) { async delete(userOrRole, reason) {
const userOrRoleId = this.channel.guild.roles.resolveId(userOrRole) ?? this.client.users.resolveId(userOrRole); 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 }); await this.client.rest.delete(Routes.channelPermission(this.channel.id, userOrRoleId), { reason });
return this.channel; return this.channel;

View File

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

View File

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

View File

@@ -2,7 +2,7 @@
const { Routes } = require('discord-api-types/v10'); const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager'); const CachedManager = require('./CachedManager');
const { TypeError, Error, ErrorCodes } = require('../errors'); const { DiscordjsTypeError, DiscordjsError, ErrorCodes } = require('../errors');
const { StageInstance } = require('../structures/StageInstance'); const { StageInstance } = require('../structures/StageInstance');
/** /**
@@ -57,8 +57,8 @@ class StageInstanceManager extends CachedManager {
*/ */
async create(channel, options) { async create(channel, options) {
const channelId = this.guild.channels.resolveId(channel); const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new Error(ErrorCodes.StageChannelResolve); if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve);
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 { topic, privacyLevel, sendStartNotification } = options; let { topic, privacyLevel, sendStartNotification } = options;
const data = await this.client.rest.post(Routes.stageInstances(), { const data = await this.client.rest.post(Routes.stageInstances(), {
@@ -86,7 +86,7 @@ class StageInstanceManager extends CachedManager {
*/ */
async fetch(channel, { cache = true, force = false } = {}) { async fetch(channel, { cache = true, force = false } = {}) {
const channelId = this.guild.channels.resolveId(channel); const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new Error(ErrorCodes.StageChannelResolve); if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve);
if (!force) { if (!force) {
const existing = this.cache.find(stageInstance => stageInstance.channelId === channelId); const existing = this.cache.find(stageInstance => stageInstance.channelId === channelId);
@@ -116,9 +116,9 @@ class StageInstanceManager extends CachedManager {
* .catch(console.error); * .catch(console.error);
*/ */
async edit(channel, options) { 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); 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; let { topic, privacyLevel } = options;
@@ -145,7 +145,7 @@ class StageInstanceManager extends CachedManager {
*/ */
async delete(channel) { async delete(channel) {
const channelId = this.guild.channels.resolveId(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)); 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 { makeURLSearchParams } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10'); const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager'); const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors'); const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const ThreadChannel = require('../structures/ThreadChannel'); const ThreadChannel = require('../structures/ThreadChannel');
/** /**
@@ -162,7 +162,7 @@ class ThreadManager extends CachedManager {
query.set('before', timestamp); query.set('before', timestamp);
} }
} catch { } 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 { Collection } = require('@discordjs/collection');
const { Routes } = require('discord-api-types/v10'); const { Routes } = require('discord-api-types/v10');
const CachedManager = require('./CachedManager'); const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors'); const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const ThreadMember = require('../structures/ThreadMember'); const ThreadMember = require('../structures/ThreadMember');
/** /**
@@ -95,7 +95,7 @@ class ThreadMemberManager extends CachedManager {
*/ */
async add(member, reason) { async add(member, reason) {
const id = member === '@me' ? member : this.client.users.resolveId(member); 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 }); await this.client.rest.put(Routes.threadMembers(this.thread.id, id), { reason });
return id; return id;
} }

View File

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

View File

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

View File

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

View File

@@ -7,7 +7,7 @@ const process = require('node:process');
const { setTimeout: sleep } = require('node:timers/promises'); const { setTimeout: sleep } = require('node:timers/promises');
const { Collection } = require('@discordjs/collection'); const { Collection } = require('@discordjs/collection');
const Shard = require('./Shard'); const Shard = require('./Shard');
const { Error, TypeError, RangeError, ErrorCodes } = require('../errors'); const { DiscordjsError, DiscordjsTypeError, DiscordjsRangeError, ErrorCodes } = require('../errors');
const { mergeDefault, fetchRecommendedShardCount } = require('../util/Util'); const { mergeDefault, fetchRecommendedShardCount } = require('../util/Util');
/** /**
@@ -64,10 +64,10 @@ class ShardingManager extends EventEmitter {
* @type {string} * @type {string}
*/ */
this.file = file; 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); if (!path.isAbsolute(file)) this.file = path.resolve(process.cwd(), file);
const stats = fs.statSync(this.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 * List of shards this sharding manager spawns
@@ -76,18 +76,18 @@ class ShardingManager extends EventEmitter {
this.shardList = options.shardList ?? 'auto'; this.shardList = options.shardList ?? 'auto';
if (this.shardList !== 'auto') { if (this.shardList !== 'auto') {
if (!Array.isArray(this.shardList)) { 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)]; this.shardList = [...new Set(this.shardList)];
if (this.shardList.length < 1) { 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 ( if (
this.shardList.some( this.shardList.some(
shardId => typeof shardId !== 'number' || isNaN(shardId) || !Number.isInteger(shardId) || shardId < 0, 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'; this.totalShards = options.totalShards || 'auto';
if (this.totalShards !== 'auto') { if (this.totalShards !== 'auto') {
if (typeof this.totalShards !== 'number' || isNaN(this.totalShards)) { 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) { 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)) { 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; this.mode = options.mode;
if (this.mode !== 'process' && this.mode !== 'worker') { 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); amount = await fetchRecommendedShardCount(this.token);
} else { } else {
if (typeof amount !== 'number' || isNaN(amount)) { 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)) { 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 // 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) { if (this.shardList === 'auto' || this.totalShards === 'auto' || this.totalShards !== amount) {
this.shardList = [...Array(amount).keys()]; this.shardList = [...Array(amount).keys()];
} }
@@ -208,7 +208,7 @@ class ShardingManager extends EventEmitter {
} }
if (this.shardList.some(shardId => shardId >= amount)) { if (this.shardList.some(shardId => shardId >= amount)) {
throw new RangeError( throw new DiscordjsRangeError(
ErrorCodes.ClientInvalidOption, ErrorCodes.ClientInvalidOption,
'Amount of shards', 'Amount of shards',
'bigger than the highest shardId in the shardList option.', '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 * @returns {Promise<*|Array<*>>} Results of the script execution
*/ */
broadcastEval(script, options = {}) { 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); return this._performOnShards('eval', [`(${script})(this, ${JSON.stringify(options.context)})`], options.shard);
} }
@@ -279,14 +281,16 @@ class ShardingManager extends EventEmitter {
* @private * @private
*/ */
_performOnShards(method, args, shard) { _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 (typeof shard === 'number') {
if (this.shards.has(shard)) return this.shards.get(shard)[method](...args); if (this.shards.has(shard)) return this.shards.get(shard)[method](...args);
return Promise.reject(new 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 = []; const promises = [];
for (const sh of this.shards.values()) promises.push(sh[method](...args)); 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 { InteractionResponseType, Routes } = require('discord-api-types/v10');
const BaseInteraction = require('./BaseInteraction'); const BaseInteraction = require('./BaseInteraction');
const CommandInteractionOptionResolver = require('./CommandInteractionOptionResolver'); const CommandInteractionOptionResolver = require('./CommandInteractionOptionResolver');
const { Error, ErrorCodes } = require('../errors'); const { DiscordjsError, ErrorCodes } = require('../errors');
/** /**
* Represents an autocomplete interaction. * Represents an autocomplete interaction.
@@ -81,7 +81,7 @@ class AutocompleteInteraction extends BaseInteraction {
* .catch(console.error); * .catch(console.error);
*/ */
async respond(options) { 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), { await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: { body: {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,7 @@
'use strict'; 'use strict';
const { InteractionType } = require('discord-api-types/v10'); const { InteractionType } = require('discord-api-types/v10');
const { Error, ErrorCodes } = require('../errors'); const { DiscordjsError, ErrorCodes } = require('../errors');
/** /**
* Represents an interaction's response * Represents an interaction's response
@@ -34,7 +34,7 @@ class InteractionResponse {
collector.once('end', (interactions, reason) => { collector.once('end', (interactions, reason) => {
const interaction = interactions.first(); const interaction = interactions.first();
if (interaction) resolve(interaction); 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 { GuildScheduledEvent } = require('./GuildScheduledEvent');
const IntegrationApplication = require('./IntegrationApplication'); const IntegrationApplication = require('./IntegrationApplication');
const InviteStageInstance = require('./InviteStageInstance'); const InviteStageInstance = require('./InviteStageInstance');
const { Error, ErrorCodes } = require('../errors'); const { DiscordjsError, ErrorCodes } = require('../errors');
/** /**
* Represents an invitation to a guild channel. * Represents an invitation to a guild channel.
@@ -234,7 +234,7 @@ class Invite extends Base {
get deletable() { get deletable() {
const guild = this.guild; const guild = this.guild;
if (!guild || !this.client.guilds.cache.has(guild.id)) return false; 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( return Boolean(
this.channel?.permissionsFor(this.client.user).has(PermissionFlagsBits.ManageChannels, false) || this.channel?.permissionsFor(this.client.user).has(PermissionFlagsBits.ManageChannels, false) ||
guild.members.me.permissions.has(PermissionFlagsBits.ManageGuild), guild.members.me.permissions.has(PermissionFlagsBits.ManageGuild),

View File

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

View File

@@ -5,7 +5,7 @@ const { isJSONEncodable } = require('@discordjs/builders');
const { lazy } = require('@discordjs/util'); const { lazy } = require('@discordjs/util');
const { MessageFlags } = require('discord-api-types/v10'); const { MessageFlags } = require('discord-api-types/v10');
const ActionRowBuilder = require('./ActionRowBuilder'); const ActionRowBuilder = require('./ActionRowBuilder');
const { RangeError, ErrorCodes } = require('../errors'); const { DiscordjsRangeError, ErrorCodes } = require('../errors');
const DataResolver = require('../util/DataResolver'); const DataResolver = require('../util/DataResolver');
const MessageFlagsBitField = require('../util/MessageFlagsBitField'); const MessageFlagsBitField = require('../util/MessageFlagsBitField');
const { basename, verifyString } = require('../util/Util'); const { basename, verifyString } = require('../util/Util');
@@ -108,7 +108,7 @@ class MessagePayload {
if (this.options.content === null) { if (this.options.content === null) {
content = ''; content = '';
} else if (typeof this.options.content !== 'undefined') { } 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; return content;
@@ -130,7 +130,7 @@ class MessagePayload {
if (typeof this.options.nonce !== 'undefined') { if (typeof this.options.nonce !== 'undefined') {
nonce = this.options.nonce; nonce = this.options.nonce;
if (typeof nonce === 'number' ? !Number.isInteger(nonce) : typeof nonce !== 'string') { 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 { Collection } = require('@discordjs/collection');
const { ComponentType } = require('discord-api-types/v10'); 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 * Represents the serialized fields from a modal submit interaction
@@ -33,10 +33,10 @@ class ModalSubmitFields {
*/ */
getField(customId, type) { getField(customId, type) {
const field = this.fields.get(customId); 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) { 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; return field;

View File

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

View File

@@ -1,7 +1,7 @@
'use strict'; 'use strict';
const { BaseChannel } = require('./BaseChannel'); const { BaseChannel } = require('./BaseChannel');
const { Error, ErrorCodes } = require('../errors'); const { DiscordjsError, ErrorCodes } = require('../errors');
/** /**
* Represents a Partial Group DM Channel on Discord. * Represents a Partial Group DM Channel on Discord.
@@ -49,11 +49,11 @@ class PartialGroupDMChannel extends BaseChannel {
} }
delete() { delete() {
return Promise.reject(new Error(ErrorCodes.DeleteGroupDMChannel)); return Promise.reject(new DiscordjsError(ErrorCodes.DeleteGroupDMChannel));
} }
fetch() { 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 { OverwriteType } = require('discord-api-types/v10');
const Base = require('./Base'); const Base = require('./Base');
const { Role } = require('./Role'); const { Role } = require('./Role');
const { TypeError, ErrorCodes } = require('../errors'); const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const PermissionsBitField = require('../util/PermissionsBitField'); 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); 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; const type = userOrRole instanceof Role ? OverwriteType.Role : OverwriteType.Member;
return { return {

View File

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

View File

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

View File

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

View File

@@ -2,7 +2,7 @@
const { ChannelType, Routes } = require('discord-api-types/v10'); const { ChannelType, Routes } = require('discord-api-types/v10');
const Base = require('./Base'); const Base = require('./Base');
const { Error, TypeError, ErrorCodes } = require('../errors'); const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
/** /**
* Represents the voice state for a Guild Member. * Represents the voice state for a Guild Member.
@@ -220,20 +220,20 @@ class VoiceState extends Base {
* @returns {Promise<VoiceState>} * @returns {Promise<VoiceState>}
*/ */
async edit(data) { 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; const target = this.client.user.id === this.id ? '@me' : this.id;
if (target !== '@me' && typeof data.requestToSpeak !== 'undefined') { if (target !== '@me' && typeof data.requestToSpeak !== 'undefined') {
throw new Error(ErrorCodes.VoiceStateNotOwn); throw new DiscordjsError(ErrorCodes.VoiceStateNotOwn);
} }
if (!['boolean', 'undefined'].includes(typeof data.requestToSpeak)) { 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)) { 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), { 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 { DiscordSnowflake } = require('@sapphire/snowflake');
const { Routes, WebhookType } = require('discord-api-types/v10'); const { Routes, WebhookType } = require('discord-api-types/v10');
const MessagePayload = require('./MessagePayload'); const MessagePayload = require('./MessagePayload');
const { Error, ErrorCodes } = require('../errors'); const { DiscordjsError, ErrorCodes } = require('../errors');
const DataResolver = require('../util/DataResolver'); const DataResolver = require('../util/DataResolver');
const getMessage = lazy(() => require('./Message').Message); const getMessage = lazy(() => require('./Message').Message);
@@ -190,7 +190,7 @@ class Webhook {
* .catch(console.error); * .catch(console.error);
*/ */
async send(options) { async send(options) {
if (!this.token) throw new Error(ErrorCodes.WebhookTokenUnavailable); if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable);
let messagePayload; let messagePayload;
@@ -231,7 +231,7 @@ class Webhook {
* @see {@link https://api.slack.com/messaging/webhooks} * @see {@link https://api.slack.com/messaging/webhooks}
*/ */
async sendSlackMessage(body) { 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'), { const data = await this.client.rest.post(Routes.webhookPlatform(this.id, this.token, 'slack'), {
query: makeURLSearchParams({ wait: true }), query: makeURLSearchParams({ wait: true }),
@@ -287,7 +287,7 @@ class Webhook {
* @returns {Promise<Message>} Returns the message sent by this webhook * @returns {Promise<Message>} Returns the message sent by this webhook
*/ */
async fetchMessage(message, { threadId } = {}) { 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), { const data = await this.client.rest.get(Routes.webhookMessage(this.id, this.token, message), {
query: threadId ? makeURLSearchParams({ thread_id: threadId }) : undefined, query: threadId ? makeURLSearchParams({ thread_id: threadId }) : undefined,
@@ -308,7 +308,7 @@ class Webhook {
* @returns {Promise<Message>} Returns the message edited by this webhook * @returns {Promise<Message>} Returns the message edited by this webhook
*/ */
async editMessage(message, options) { async editMessage(message, options) {
if (!this.token) throw new Error(ErrorCodes.WebhookTokenUnavailable); if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable);
let messagePayload; let messagePayload;
@@ -359,7 +359,7 @@ class Webhook {
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async deleteMessage(message, threadId) { 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( await this.client.rest.delete(
Routes.webhookMessage(this.id, this.token, typeof message === 'string' ? message : message.id), Routes.webhookMessage(this.id, this.token, typeof message === 'string' ? message : message.id),

View File

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

View File

@@ -2,7 +2,7 @@
const { isJSONEncodable } = require('@discordjs/builders'); const { isJSONEncodable } = require('@discordjs/builders');
const { InteractionResponseType, MessageFlags, Routes, InteractionType } = require('discord-api-types/v10'); 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 InteractionCollector = require('../InteractionCollector');
const InteractionResponse = require('../InteractionResponse'); const InteractionResponse = require('../InteractionResponse');
const MessagePayload = require('../MessagePayload'); const MessagePayload = require('../MessagePayload');
@@ -64,7 +64,7 @@ class InteractionResponses {
* .catch(console.error); * .catch(console.error);
*/ */
async deferReply(options = {}) { 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; this.ephemeral = options.ephemeral ?? false;
await this.client.rest.post(Routes.interactionCallback(this.id, this.token), { await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: { body: {
@@ -99,7 +99,7 @@ class InteractionResponses {
* .catch(console.error); * .catch(console.error);
*/ */
async reply(options) { 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; this.ephemeral = options.ephemeral ?? false;
let messagePayload; let messagePayload;
@@ -147,7 +147,7 @@ class InteractionResponses {
* .catch(console.error); * .catch(console.error);
*/ */
async editReply(options) { 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); const message = await this.webhook.editMessage('@original', options);
this.replied = true; this.replied = true;
return message; return message;
@@ -164,7 +164,7 @@ class InteractionResponses {
* .catch(console.error); * .catch(console.error);
*/ */
async deleteReply() { async deleteReply() {
if (this.ephemeral) throw new Error(ErrorCodes.InteractionEphemeralReplied); if (this.ephemeral) throw new DiscordjsError(ErrorCodes.InteractionEphemeralReplied);
await this.webhook.deleteMessage('@original'); await this.webhook.deleteMessage('@original');
} }
@@ -174,7 +174,7 @@ class InteractionResponses {
* @returns {Promise<Message>} * @returns {Promise<Message>}
*/ */
followUp(options) { 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); return this.webhook.send(options);
} }
@@ -189,7 +189,7 @@ class InteractionResponses {
* .catch(console.error); * .catch(console.error);
*/ */
async deferUpdate(options = {}) { 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), { await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: { body: {
type: InteractionResponseType.DeferredMessageUpdate, type: InteractionResponseType.DeferredMessageUpdate,
@@ -215,7 +215,7 @@ class InteractionResponses {
* .catch(console.error); * .catch(console.error);
*/ */
async update(options) { 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; let messagePayload;
if (options instanceof MessagePayload) messagePayload = options; if (options instanceof MessagePayload) messagePayload = options;
@@ -242,7 +242,7 @@ class InteractionResponses {
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async showModal(modal) { 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), { await this.client.rest.post(Routes.interactionCallback(this.id, this.token), {
body: { body: {
type: InteractionResponseType.Modal, type: InteractionResponseType.Modal,
@@ -272,14 +272,14 @@ class InteractionResponses {
* .catch(console.error); * .catch(console.error);
*/ */
awaitModalSubmit(options) { 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 }; const _options = { ...options, max: 1, interactionType: InteractionType.ModalSubmit };
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const collector = new InteractionCollector(this.client, _options); const collector = new InteractionCollector(this.client, _options);
collector.once('end', (interactions, reason) => { collector.once('end', (interactions, reason) => {
const interaction = interactions.first(); const interaction = interactions.first();
if (interaction) resolve(interaction); 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 { Collection } = require('@discordjs/collection');
const { DiscordSnowflake } = require('@sapphire/snowflake'); const { DiscordSnowflake } = require('@sapphire/snowflake');
const { InteractionType, Routes } = require('discord-api-types/v10'); 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 InteractionCollector = require('../InteractionCollector');
const MessageCollector = require('../MessageCollector'); const MessageCollector = require('../MessageCollector');
const MessagePayload = require('../MessagePayload'); const MessagePayload = require('../MessagePayload');
@@ -273,7 +273,7 @@ class TextBasedChannel {
collector.once('end', (interactions, reason) => { collector.once('end', (interactions, reason) => {
const interaction = interactions.first(); const interaction = interactions.first();
if (interaction) resolve(interaction); 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 }); const msgs = await this.messages.fetch({ limit: messages });
return this.bulkDelete(msgs, filterOld); return this.bulkDelete(msgs, filterOld);
} }
throw new TypeError(ErrorCodes.MessageBulkDeleteType); throw new DiscordjsTypeError(ErrorCodes.MessageBulkDeleteType);
} }
/** /**

View File

@@ -1,6 +1,6 @@
'use strict'; 'use strict';
const { RangeError, ErrorCodes } = require('../errors'); const { DiscordjsRangeError, ErrorCodes } = require('../errors');
/** /**
* Data structure that makes it easy to interact with a bitfield. * 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 (typeof this.Flags[bit] !== 'undefined') return this.Flags[bit];
if (!isNaN(bit)) return typeof DefaultBit === 'bigint' ? BigInt(bit) : Number(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 fs = require('node:fs/promises');
const path = require('node:path'); const path = require('node:path');
const { fetch } = require('undici'); const { fetch } = require('undici');
const { Error: DiscordError, TypeError, ErrorCodes } = require('../errors'); const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');
const Invite = require('../structures/Invite'); const Invite = require('../structures/Invite');
/** /**
@@ -129,11 +129,11 @@ class DataResolver extends null {
const file = path.resolve(resource); const file = path.resolve(resource);
const stats = await fs.stat(file); 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) }; return { data: await fs.readFile(file) };
} }
throw new TypeError(ErrorCodes.ReqResourceType); throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);
} }
} }

View File

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

View File

@@ -3,7 +3,7 @@
const { setInterval, clearInterval } = require('node:timers'); const { setInterval, clearInterval } = require('node:timers');
const { ThreadChannelTypes, SweeperKeys } = require('./Constants'); const { ThreadChannelTypes, SweeperKeys } = require('./Constants');
const Events = require('./Events'); const Events = require('./Events');
const { TypeError, ErrorCodes } = require('../errors'); const { DiscordjsTypeError, ErrorCodes } = require('../errors');
/** /**
* @typedef {Function} GlobalSweepFilter * @typedef {Function} GlobalSweepFilter
@@ -131,7 +131,7 @@ class Sweepers {
*/ */
sweepMessages(filter) { sweepMessages(filter) {
if (typeof filter !== 'function') { if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function'); throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
} }
let channels = 0; let channels = 0;
let messages = 0; let messages = 0;
@@ -162,7 +162,7 @@ class Sweepers {
*/ */
sweepReactions(filter) { sweepReactions(filter) {
if (typeof filter !== 'function') { if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function'); throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
} }
let channels = 0; let channels = 0;
let messages = 0; let messages = 0;
@@ -210,7 +210,7 @@ class Sweepers {
*/ */
sweepThreadMembers(filter) { sweepThreadMembers(filter) {
if (typeof filter !== 'function') { if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function'); throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
} }
let threads = 0; let threads = 0;
@@ -240,7 +240,7 @@ class Sweepers {
*/ */
sweepThreads(filter) { sweepThreads(filter) {
if (typeof filter !== 'function') { if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function'); throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
} }
let threads = 0; let threads = 0;
@@ -262,7 +262,7 @@ class Sweepers {
*/ */
sweepUsers(filter) { sweepUsers(filter) {
if (typeof filter !== 'function') { 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); const users = this.client.users.cache.sweep(filter);
@@ -313,13 +313,13 @@ class Sweepers {
excludeFromSweep = () => false, excludeFromSweep = () => false,
} = {}) { } = {}) {
if (typeof lifetime !== 'number') { if (typeof lifetime !== 'number') {
throw new TypeError(ErrorCodes.InvalidType, 'lifetime', 'number'); throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'lifetime', 'number');
} }
if (typeof getComparisonTimestamp !== 'function') { if (typeof getComparisonTimestamp !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'getComparisonTimestamp', 'function'); throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'getComparisonTimestamp', 'function');
} }
if (typeof excludeFromSweep !== 'function') { if (typeof excludeFromSweep !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'excludeFromSweep', 'function'); throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'excludeFromSweep', 'function');
} }
return () => { return () => {
if (lifetime <= 0) return null; if (lifetime <= 0) return null;
@@ -391,7 +391,7 @@ class Sweepers {
*/ */
_sweepGuildDirectProp(key, filter, { emit = true, outputName } = {}) { _sweepGuildDirectProp(key, filter, { emit = true, outputName } = {}) {
if (typeof filter !== 'function') { if (typeof filter !== 'function') {
throw new TypeError(ErrorCodes.InvalidType, 'filter', 'function'); throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'filter', 'function');
} }
let guilds = 0; let guilds = 0;
@@ -419,20 +419,20 @@ class Sweepers {
_validateProperties(key) { _validateProperties(key) {
const props = this.options[key]; const props = this.options[key];
if (typeof props !== 'object') { 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') { 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 // 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 (['invites', 'messages', 'threads'].includes(key) && !('filter' in props)) {
if (typeof props.lifetime !== 'number') { if (typeof props.lifetime !== 'number') {
throw new TypeError(ErrorCodes.InvalidType, `sweepers.${key}.lifetime`, 'number'); throw new DiscordjsTypeError(ErrorCodes.InvalidType, `sweepers.${key}.lifetime`, 'number');
} }
return; return;
} }
if (typeof props.filter !== 'function') { 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(() => { this.intervals[intervalKey] = setInterval(() => {
const sweepFn = opts.filter(); const sweepFn = opts.filter();
if (sweepFn === null) return; 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); this[sweepKey](sweepFn);
}, opts.interval * 1_000).unref(); }, 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 { ChannelType, RouteBases, Routes } = require('discord-api-types/v10');
const { fetch } = require('undici'); const { fetch } = require('undici');
const Colors = require('./Colors'); 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; const isObject = d => typeof d === 'object' && d !== null;
/** /**
@@ -223,13 +223,13 @@ function escapeSpoiler(text) {
* @returns {Promise<number>} The recommended number of shards * @returns {Promise<number>} The recommended number of shards
*/ */
async function fetchRecommendedShardCount(token, { guildsPerShard = 1_000, multipleOf = 1 } = {}) { 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(), { const response = await fetch(RouteBases.api + Routes.gatewayBot(), {
method: 'GET', method: 'GET',
headers: { Authorization: `Bot ${token.replace(/^Bot\s*/i, '')}` }, headers: { Authorization: `Bot ${token.replace(/^Bot\s*/i, '')}` },
}); });
if (!response.ok) { if (!response.ok) {
if (response.status === 401) throw new DiscordError(ErrorCodes.TokenInvalid); if (response.status === 401) throw new DiscordjsError(ErrorCodes.TokenInvalid);
throw response; throw response;
} }
const { shards } = await response.json(); const { shards } = await response.json();
@@ -413,8 +413,8 @@ function resolveColor(color) {
color = (color[0] << 16) + (color[1] << 8) + color[2]; color = (color[0] << 16) + (color[1] << 8) + color[2];
} }
if (color < 0 || color > 0xffffff) throw new RangeError(ErrorCodes.ColorRange); if (color < 0 || color > 0xffffff) throw new DiscordjsRangeError(ErrorCodes.ColorRange);
else if (Number.isNaN(color)) throw new TypeError(ErrorCodes.ColorConvert); else if (Number.isNaN(color)) throw new DiscordjsTypeError(ErrorCodes.ColorConvert);
return color; return color;
} }