{"record":{"id":"d2afa095f5b3c843","repo":"discordjs/discord.js","slug":"shardingworkerexists","errorCode":"ShardingWorkerExists","errorMessage":"ShardingWorkerExists","messagePattern":"ShardingWorkerExists","errorType":"error_code","errorClass":"DiscordjsError","httpStatus":null,"severity":"error","filePath":"packages/discord.js/src/sharding/Shard.js","lineNumber":143,"sourceCode":"     * Listener function for the {@link ChildProcess}' `exit` event\n     *\n     * @type {Function}\n     * @private\n     */\n    this._exitListener = null;\n  }\n\n  /**\n   * Forks a child process or creates a worker thread for the shard.\n   * <warn>You should not need to call this manually.</warn>\n   *\n   * @param {number} [timeout=30000] The amount in milliseconds to wait until the {@link Client} has become ready\n   * before resolving (`-1` or `Infinity` for no wait)\n   * @returns {Promise<ChildProcess>}\n   */\n  async spawn(timeout = 30_000) {\n    if (this.process) throw new DiscordjsError(ErrorCodes.ShardingProcessExists, this.id);\n    if (this.worker) throw new DiscordjsError(ErrorCodes.ShardingWorkerExists, this.id);\n\n    this._exitListener = this._handleExit.bind(this, undefined, timeout);\n\n    switch (this.manager.mode) {\n      case 'process':\n        this.process = childProcess\n          .fork(path.resolve(this.manager.file), this.args, {\n            env: this.env,\n            execArgv: this.execArgv,\n            silent: this.silent,\n          })\n          .on('message', this._handleMessage.bind(this))\n          .on('exit', this._exitListener);\n        break;\n      case 'worker':\n        this.worker = new Worker(path.resolve(this.manager.file), {\n          workerData: this.env,\n          env: SHARE_ENV,","sourceCodeStart":125,"sourceCodeEnd":161,"githubUrl":"https://github.com/discordjs/discord.js/blob/a81ed8a306d37fdc746e26a634b6a42164ba2c8c/packages/discord.js/src/sharding/Shard.js#L125-L161","documentation":"ShardingWorkerExists is thrown by Shard.spawn() when the shard already has a live Worker thread attached (this.worker is set). It is the worker-mode counterpart of ShardingProcessExists and prevents starting a second worker thread for the same shard, which would break IPC message routing.","triggerScenarios":"Calling spawn() on a shard whose manager.mode is 'worker' while this.worker is still set; calling manager.spawn() twice; concurrent respawn()/spawn() calls racing past the guard; spawning after a previous spawn() that hasn't exited.","commonSituations":"Using ShardingManager with mode:'worker' and re-running the bootstrap script (e.g., PM2 or nodemon restart logic that doesn't kill the manager); hot-reload wrappers that re-instantiate manager.spawn() without tearing down the old manager.","solutions":["Check shard.worker is null/undefined before spawning","Await the previous spawn/exit (or call respawn()) instead of spawning again","Tear down the old ShardingManager (kill workers) before creating and spawning a new one","Avoid spawning the same manager from multiple entry points (e.g., both main and a warmup module)"],"exampleFix":"// before\nif (shouldRestart) manager.spawn(); // throws ShardingWorkerExists\n// after\nif (shouldRestart) await Promise.all(manager.shards.map(s => s.respawn()));","handlingStrategy":"validation","validationCode":"function canSpawnWorker(shard) { return shard.worker == null && shard.process == null; }\nif (canSpawnWorker(shard)) await shard.spawn();","typeGuard":"function hasLiveWorker(shard) { return shard.worker != null; }","tryCatchPattern":"try {\n  await shard.spawn();\n} catch (err) {\n  if (err.code === 'ShardingWorkerExists') {\n    return shard.worker; // worker already live\n  }\n  throw err;\n}","preventionTips":["Kill the old ShardingManager/workers before re-running bootstrap code (especially under PM2/nodemon)","Use respawn() for restarts instead of spawn()","Check shard.worker before spawn in worker mode","Centralize manager creation in a single entry point"],"tags":["sharding","discordjs","worker-threads","double-spawn"],"backgroundTag":"already-spawned-shard","analyzedSha":"a81ed8a306d37fdc746e26a634b6a42164ba2c8c","analyzedAt":"2026-08-30T04:07:22.193Z","schemaVersion":2},"datasetVersion":"2026-08-30T08:17:16.595Z"}