Skip to content

Commit

Permalink
refactor: rename Error to DiscordjsError internally (#8706)
Browse files Browse the repository at this point in the history
* refactor: rename Error to DiscordjsError internally

* chore: remove globalThis usage

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
  • Loading branch information
almeidx and kodiakhq[bot] committed Oct 6, 2022
1 parent e745b95 commit aec44a0
Show file tree
Hide file tree
Showing 60 changed files with 335 additions and 307 deletions.
4 changes: 2 additions & 2 deletions packages/discord.js/src/client/BaseClient.js
Expand Up @@ -2,7 +2,7 @@

const EventEmitter = require('node:events');
const { REST } = require('@discordjs/rest');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const Options = require('../util/Options');
const { mergeDefault, flatten } = require('../util/Util');

Expand All @@ -15,7 +15,7 @@ class BaseClient extends EventEmitter {
super({ captureRejections: true });

if (typeof options !== 'object' || options === null) {
throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
}

/**
Expand Down
40 changes: 20 additions & 20 deletions packages/discord.js/src/client/Client.js
Expand Up @@ -8,7 +8,7 @@ const BaseClient = require('./BaseClient');
const ActionsManager = require('./actions/ActionsManager');
const ClientVoiceManager = require('./voice/ClientVoiceManager');
const WebSocketManager = require('./websocket/WebSocketManager');
const { Error, TypeError, RangeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, DiscordjsRangeError, ErrorCodes } = require('../errors');
const BaseGuildEmojiManager = require('../managers/BaseGuildEmojiManager');
const ChannelManager = require('../managers/ChannelManager');
const GuildManager = require('../managers/GuildManager');
Expand Down Expand Up @@ -211,7 +211,7 @@ class Client extends BaseClient {
* client.login('my token');
*/
async login(token = this.token) {
if (!token || typeof token !== 'string') throw new Error(ErrorCodes.TokenInvalid);
if (!token || typeof token !== 'string') throw new DiscordjsError(ErrorCodes.TokenInvalid);
this.token = token = token.replace(/^(Bot|Bearer)\s*/i, '');
this.rest.setToken(token);
this.emit(
Expand Down Expand Up @@ -366,7 +366,7 @@ class Client extends BaseClient {
*/
async fetchGuildPreview(guild) {
const id = this.guilds.resolveId(guild);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable');
const data = await this.rest.get(Routes.guildPreview(id));
return new GuildPreview(this, data);
}
Expand All @@ -378,7 +378,7 @@ class Client extends BaseClient {
*/
async fetchGuildWidget(guild) {
const id = this.guilds.resolveId(guild);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable');
const data = await this.rest.get(Routes.guildWidgetJSON(id));
return new Widget(this, data);
}
Expand Down Expand Up @@ -413,23 +413,23 @@ class Client extends BaseClient {
* console.log(`Generated bot invite link: ${link}`);
*/
generateInvite(options = {}) {
if (typeof options !== 'object') throw new TypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (!this.application) throw new Error(ErrorCodes.ClientNotReady, 'generate an invite link');
if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true);
if (!this.application) throw new DiscordjsError(ErrorCodes.ClientNotReady, 'generate an invite link');

const { scopes } = options;
if (typeof scopes === 'undefined') {
throw new TypeError(ErrorCodes.InvalidMissingScopes);
throw new DiscordjsTypeError(ErrorCodes.InvalidMissingScopes);
}
if (!Array.isArray(scopes)) {
throw new TypeError(ErrorCodes.InvalidType, 'scopes', 'Array of Invite Scopes', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'scopes', 'Array of Invite Scopes', true);
}
if (!scopes.some(scope => [OAuth2Scopes.Bot, OAuth2Scopes.ApplicationsCommands].includes(scope))) {
throw new TypeError(ErrorCodes.InvalidMissingScopes);
throw new DiscordjsTypeError(ErrorCodes.InvalidMissingScopes);
}
const validScopes = Object.values(OAuth2Scopes);
const invalidScope = scopes.find(scope => !validScopes.includes(scope));
if (invalidScope) {
throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'scopes', invalidScope);
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'scopes', invalidScope);
}

const query = makeURLSearchParams({
Expand All @@ -445,7 +445,7 @@ class Client extends BaseClient {

if (options.guild) {
const guildId = this.guilds.resolveId(options.guild);
if (!guildId) throw new TypeError(ErrorCodes.InvalidType, 'options.guild', 'GuildResolvable');
if (!guildId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options.guild', 'GuildResolvable');
query.set('guild_id', guildId);
}

Expand Down Expand Up @@ -477,31 +477,31 @@ class Client extends BaseClient {
*/
_validateOptions(options = this.options) {
if (typeof options.intents === 'undefined') {
throw new TypeError(ErrorCodes.ClientMissingIntents);
throw new DiscordjsTypeError(ErrorCodes.ClientMissingIntents);
} else {
options.intents = IntentsBitField.resolve(options.intents);
}
if (typeof options.shardCount !== 'number' || isNaN(options.shardCount) || options.shardCount < 1) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'shardCount', 'a number greater than or equal to 1');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'shardCount', 'a number greater than or equal to 1');
}
if (options.shards && !(options.shards === 'auto' || Array.isArray(options.shards))) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'shards', "'auto', a number or array of numbers");
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'shards', "'auto', a number or array of numbers");
}
if (options.shards && !options.shards.length) throw new RangeError(ErrorCodes.ClientInvalidProvidedShards);
if (options.shards && !options.shards.length) throw new DiscordjsRangeError(ErrorCodes.ClientInvalidProvidedShards);
if (typeof options.makeCache !== 'function') {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'makeCache', 'a function');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'makeCache', 'a function');
}
if (typeof options.sweepers !== 'object' || options.sweepers === null) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'sweepers', 'an object');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'sweepers', 'an object');
}
if (!Array.isArray(options.partials)) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'partials', 'an Array');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'partials', 'an Array');
}
if (typeof options.waitGuildTimeout !== 'number' || isNaN(options.waitGuildTimeout)) {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'waitGuildTimeout', 'a number');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'waitGuildTimeout', 'a number');
}
if (typeof options.failIfNotExists !== 'boolean') {
throw new TypeError(ErrorCodes.ClientInvalidOption, 'failIfNotExists', 'a boolean');
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'failIfNotExists', 'a boolean');
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/discord.js/src/client/WebhookClient.js
@@ -1,7 +1,7 @@
'use strict';

const BaseClient = require('./BaseClient');
const { Error, ErrorCodes } = require('../errors');
const { DiscordjsError, ErrorCodes } = require('../errors');
const Webhook = require('../structures/Webhook');
const { parseWebhookURL } = require('../util/Util');

Expand Down Expand Up @@ -48,7 +48,7 @@ class WebhookClient extends BaseClient {
if ('url' in data) {
const parsed = parseWebhookURL(data.url);
if (!parsed) {
throw new Error(ErrorCodes.WebhookURLInvalid);
throw new DiscordjsError(ErrorCodes.WebhookURLInvalid);
}

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

module.exports = {
Error: makeDiscordjsError(Error),
TypeError: makeDiscordjsError(TypeError),
RangeError: makeDiscordjsError(RangeError),
DiscordjsError: makeDiscordjsError(Error),
DiscordjsTypeError: makeDiscordjsError(TypeError),
DiscordjsRangeError: makeDiscordjsError(RangeError),
};
7 changes: 3 additions & 4 deletions packages/discord.js/src/index.js
Expand Up @@ -11,10 +11,9 @@ exports.ShardingManager = require('./sharding/ShardingManager');
exports.WebhookClient = require('./client/WebhookClient');

// Errors
const { Error, TypeError, RangeError } = require('./errors/DJSError');
exports.DiscordjsError = Error;
exports.DiscordjsTypeError = TypeError;
exports.DiscordjsRangeError = RangeError;
exports.DiscordjsError = require('./errors/DJSError').DiscordjsError;
exports.DiscordjsTypeError = require('./errors/DJSError').DiscordjsTypeError;
exports.DiscordjsRangeError = require('./errors/DJSError').DiscordjsRangeError;
exports.DiscordjsErrorCodes = require('./errors/ErrorCodes');

// Utilities
Expand Down
6 changes: 3 additions & 3 deletions packages/discord.js/src/managers/ApplicationCommandManager.js
Expand Up @@ -6,7 +6,7 @@ const { makeURLSearchParams } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v10');
const ApplicationCommandPermissionsManager = require('./ApplicationCommandPermissionsManager');
const CachedManager = require('./CachedManager');
const { TypeError, ErrorCodes } = require('../errors');
const { DiscordjsTypeError, ErrorCodes } = require('../errors');
const ApplicationCommand = require('../structures/ApplicationCommand');
const PermissionsBitField = require('../util/PermissionsBitField');

Expand Down Expand Up @@ -193,7 +193,7 @@ class ApplicationCommandManager extends CachedManager {
*/
async edit(command, data, guildId) {
const id = this.resolveId(command);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');

const patched = await this.client.rest.patch(this.commandPath({ id, guildId }), {
body: this.constructor.transformCommand(data),
Expand All @@ -215,7 +215,7 @@ class ApplicationCommandManager extends CachedManager {
*/
async delete(command, guildId) {
const id = this.resolveId(command);
if (!id) throw new TypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');

await this.client.rest.delete(this.commandPath({ id, guildId }));

Expand Down
Expand Up @@ -3,7 +3,7 @@
const { Collection } = require('@discordjs/collection');
const { ApplicationCommandPermissionType, RESTJSONErrorCodes, Routes } = require('discord-api-types/v10');
const BaseManager = require('./BaseManager');
const { Error, TypeError, ErrorCodes } = require('../errors');
const { DiscordjsError, DiscordjsTypeError, ErrorCodes } = require('../errors');

/**
* Manages API methods for permissions of Application Commands.
Expand Down Expand Up @@ -153,12 +153,17 @@ class ApplicationCommandPermissionsManager extends BaseManager {
*/
async set({ guild, command, permissions, token } = {}) {
if (!token) {
throw new Error(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
}
let { guildId, commandId } = this._validateOptions(guild, command);

if (!Array.isArray(permissions)) {
throw new TypeError(ErrorCodes.InvalidType, 'permissions', 'Array of ApplicationCommandPermissions', true);
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'permissions',
'Array of ApplicationCommandPermissions',
true,
);
}

if (!commandId) {
Expand Down Expand Up @@ -190,14 +195,19 @@ class ApplicationCommandPermissionsManager extends BaseManager {
*/
async add({ guild, command, permissions, token } = {}) {
if (!token) {
throw new Error(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
}
let { guildId, commandId } = this._validateOptions(guild, command);
if (!commandId) {
commandId = this.client.user.id;
}
if (!Array.isArray(permissions)) {
throw new TypeError(ErrorCodes.InvalidType, 'permissions', 'Array of ApplicationCommandPermissions', true);
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'permissions',
'Array of ApplicationCommandPermissions',
true,
);
}

let existing = [];
Expand Down Expand Up @@ -262,22 +272,22 @@ class ApplicationCommandPermissionsManager extends BaseManager {
*/
async remove({ guild, command, users, roles, channels, token } = {}) {
if (!token) {
throw new Error(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
throw new DiscordjsError(ErrorCodes.ApplicationCommandPermissionsTokenMissing);
}
let { guildId, commandId } = this._validateOptions(guild, command);
if (!commandId) {
commandId = this.client.user.id;
}

if (!users && !roles && !channels) {
throw new TypeError(ErrorCodes.InvalidType, 'users OR roles OR channels', 'Array or Resolvable', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'users OR roles OR channels', 'Array or Resolvable', true);
}

let resolvedUserIds = [];
if (Array.isArray(users)) {
for (const user of users) {
const userId = this.client.users.resolveId(user);
if (!userId) throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'users', user);
if (!userId) throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'users', user);
resolvedUserIds.push(userId);
}
}
Expand All @@ -289,9 +299,9 @@ class ApplicationCommandPermissionsManager extends BaseManager {
resolvedRoleIds.push(role);
continue;
}
if (!this.guild) throw new Error(ErrorCodes.GuildUncachedEntityResolve, 'roles');
if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'roles');
const roleId = this.guild.roles.resolveId(role);
if (!roleId) throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'users', role);
if (!roleId) throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'users', role);
resolvedRoleIds.push(roleId);
}
}
Expand All @@ -303,9 +313,9 @@ class ApplicationCommandPermissionsManager extends BaseManager {
resolvedChannelIds.push(channel);
continue;
}
if (!this.guild) throw new Error(ErrorCodes.GuildUncachedEntityResolve, 'channels');
if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'channels');
const channelId = this.guild.channels.resolveId(channel);
if (!channelId) throw new TypeError(ErrorCodes.InvalidElement, 'Array', 'channels', channel);
if (!channelId) throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'channels', channel);
resolvedChannelIds.push(channelId);
}
}
Expand Down Expand Up @@ -353,10 +363,10 @@ class ApplicationCommandPermissionsManager extends BaseManager {
*/
async has({ guild, command, permissionId, permissionType }) {
const { guildId, commandId } = this._validateOptions(guild, command);
if (!commandId) throw new TypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');
if (!commandId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable');

if (!permissionId) {
throw new TypeError(
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'permissionId',
'UserResolvable, RoleResolvable, ChannelResolvable, or Permission Constant',
Expand All @@ -366,14 +376,14 @@ class ApplicationCommandPermissionsManager extends BaseManager {
if (typeof permissionId !== 'string') {
resolvedId = this.client.users.resolveId(permissionId);
if (!resolvedId) {
if (!this.guild) throw new Error(ErrorCodes.GuildUncachedEntityResolve, 'roles');
if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'roles');
resolvedId = this.guild.roles.resolveId(permissionId);
}
if (!resolvedId) {
resolvedId = this.guild.channels.resolveId(permissionId);
}
if (!resolvedId) {
throw new TypeError(
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'permissionId',
'UserResolvable, RoleResolvable, ChannelResolvable, or Permission Constant',
Expand All @@ -394,7 +404,7 @@ class ApplicationCommandPermissionsManager extends BaseManager {

_validateOptions(guild, command) {
const guildId = this.guildId ?? this.client.guilds.resolveId(guild);
if (!guildId) throw new Error(ErrorCodes.GlobalCommandPermissions);
if (!guildId) throw new DiscordjsError(ErrorCodes.GlobalCommandPermissions);
let commandId = this.commandId;
if (command && !commandId) {
commandId = this.manager.resolveId?.(command);
Expand All @@ -403,7 +413,7 @@ class ApplicationCommandPermissionsManager extends BaseManager {
}
commandId ??= this.client.application?.commands.resolveId(command);
if (!commandId) {
throw new TypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable', true);
throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable', true);
}
}
return { guildId, commandId };
Expand Down

0 comments on commit aec44a0

Please sign in to comment.