{"record":{"id":"df420fcec42ecd78","repo":"discordjs/discord.js","slug":"shardingshardmiscalculation","errorCode":"ShardingShardMiscalculation","errorMessage":"ShardingShardMiscalculation","messagePattern":"ShardingShardMiscalculation","errorType":"error_code","errorClass":"DiscordjsError","httpStatus":null,"severity":"error","filePath":"packages/discord.js/src/sharding/ShardClientUtil.js","lineNumber":261,"sourceCode":"        'Multiple clients created in child process/worker; only the first will handle sharding helpers.',\n      );\n    } else {\n      this._singleton = new this(client, mode);\n    }\n\n    return this._singleton;\n  }\n\n  /**\n   * Get the shard id for a given guild id.\n   *\n   * @param {Snowflake} guildId Snowflake guild id to get shard id for\n   * @param {number} shardCount Number of shards\n   * @returns {number}\n   */\n  static shardIdForGuildId(guildId, shardCount) {\n    const shard = calculateShardId(guildId, shardCount);\n    if (shard < 0) throw new DiscordjsError(ErrorCodes.ShardingShardMiscalculation, shard, guildId, shardCount);\n    return shard;\n  }\n\n  /**\n   * Increments max listeners by one for a given emitter, if they are not zero.\n   *\n   * @param {Worker|ChildProcess} emitter The emitter that emits the events.\n   * @private\n   */\n  incrementMaxListeners(emitter) {\n    const maxListeners = emitter.getMaxListeners();\n    if (maxListeners !== 0) {\n      emitter.setMaxListeners(maxListeners + 1);\n    }\n  }\n\n  /**\n   * Decrements max listeners by one for a given emitter, if they are not zero.","sourceCodeStart":243,"sourceCodeEnd":279,"githubUrl":"https://github.com/discordjs/discord.js/blob/a81ed8a306d37fdc746e26a634b6a42164ba2c8c/packages/discord.js/src/sharding/ShardClientUtil.js#L243-L279","documentation":"ShardingShardMiscalculation is thrown by ShardClientUtil.shardIdForGuildId() when calculateShardId() returns a negative shard index for the given guildId and shardCount. A negative result means the inputs are invalid (negative shardCount or malformed id math), so the library refuses to return a bogus shard id.","triggerScenarios":"Passing a negative or invalid shardCount; passing a guildId that cannot be parsed into the snowflake numeric range (e.g., empty string or corrupted value producing NaN/negative math); calling with a shardCount of 0 or a user-supplied count from bad config/env.","commonSituations":"Reading SHARD_COUNT from an env var that's unset or negative; passing a malformed guild id string from user input or a webhook payload; using shardIdForGuildId with a count that doesn't match the manager's actual shardCount.","solutions":["Validate shardCount is a positive integer before calling (Number.isInteger(count) && count > 0)","Validate guildId matches /^\\d{17,20}$/ before calling","Use manager.shardCount (or ShardClientUtil.shardCount) instead of hand-rolled config values","Sanitize user-supplied ids with SnowflakeUtil or BigInt parsing before computing the shard id"],"exampleFix":"// before\nconst shardId = ShardClientUtil.shardIdForGuildId(guildId, Number(process.env.SHARD_COUNT));\n// after\nconst shardCount = Number(process.env.SHARD_COUNT);\nif (!Number.isInteger(shardCount) || shardCount <= 0) throw new Error('Invalid SHARD_COUNT');\nif (!/^\\d{17,20}$/.test(guildId)) throw new Error('Invalid guild id');\nconst shardId = ShardClientUtil.shardIdForGuildId(guildId, shardCount);","handlingStrategy":"validation","validationCode":"function isValidGuildShardInput(guildId, shardCount) {\n  return /^\\d{17,20}$/.test(String(guildId)) && Number.isInteger(shardCount) && shardCount > 0;\n}\nif (isValidGuildShardInput(guildId, shardCount)) {\n  const shardId = ShardClientUtil.shardIdForGuildId(guildId, shardCount);\n}","typeGuard":"function isSnowflake(value) { return typeof value === 'string' && /^\\d{17,20}$/.test(value); }\nfunction isValidShardCount(n) { return Number.isInteger(n) && n > 0; }","tryCatchPattern":"let shardId;\ntry {\n  shardId = ShardClientUtil.shardIdForGuildId(guildId, shardCount);\n} catch (err) {\n  if (err.code === 'ShardingShardMiscalculation') {\n    throw new Error(`Cannot map guild ${guildId} to shard: check shardCount (${shardCount}) and id validity`);\n  }\n  throw err;\n}","preventionTips":["Validate env/config shard counts are positive integers at startup","Sanitize guild ids (17-20 digit snowflake) from user input before shard math","Source shardCount from manager.shardCount rather than parallel config","Fail fast with your own validation message instead of letting the library error surface to users"],"tags":["sharding","discordjs","validation","snowflake","shard-count"],"backgroundTag":"invalid-shard-count","analyzedSha":"a81ed8a306d37fdc746e26a634b6a42164ba2c8c","analyzedAt":"2026-08-30T04:07:22.193Z","schemaVersion":2},"datasetVersion":"2026-08-30T08:17:16.595Z"}