{"record":{"id":"e9224d963acba47d","repo":"TencentCloud/TencentDB-Agent-Memory","slug":"user-not-found","errorCode":"user_not_found","errorMessage":"user not found: ${userId}","messagePattern":"user not found: (.+?)","errorType":"error_code","errorClass":"MetadataError","httpStatus":null,"severity":"error","filePath":"MemoryCore/src/metadata/service/metadata-service.ts","lineNumber":341,"sourceCode":"    }\n    return out;\n  }\n\n  /** internal：按实例分页列出用户（含 system_admin，不脱敏）。 */\n  async listUsersByInstance(\n    instanceId: string,\n    pagination: PaginationParams,\n    filter?: InstanceUserListFilter,\n  ): Promise<PaginatedResult<UserEntity>> {\n    void instanceId;\n    const page = await this.store.listUsers(pagination, filter);\n    return formatListResult(page, pagination);\n  }\n\n  /** 校验用户存在，否则抛 not_found。 */\n  private async requireUser(userId: string): Promise<UserEntity> {\n    const user = await this.getUserById(userId);\n    if (!user) throw new MetadataError(\"user_not_found\", `user not found: ${userId}`);\n    return user;\n  }\n\n  get rawStore(): IMetadataStore {\n    return this.store;\n  }\n\n  private async assertUserQuota(): Promise<void> {\n    const count = await this.store.countUsers();\n    const limit = this._configParams\n      ? await this._configParams.getEffectiveInt(\"quota\", \"max_users_per_instance\")\n      : this.quota.maxUsersPerInstance;\n    if (count >= limit) {\n      throw new MetadataError(\n        \"user_limit_exceeded\",\n        `user limit ${limit} reached for instance ${this.instanceId} (current: ${count})`,\n      );\n    }","sourceCodeStart":323,"sourceCodeEnd":359,"githubUrl":"https://github.com/TencentCloud/TencentDB-Agent-Memory/blob/3efcd317b84146d6a08518ac0f7ee7c8a8d200ec/MemoryCore/src/metadata/service/metadata-service.ts#L323-L359","documentation":"requireUser is a private guard in MetadataService used before user-scoped operations such as createUserKey and listUserKeys. It loads the user by id via getUserById and throws user_not_found (a not_found MetadataError) when no user record matches, preventing key operations against nonexistent users.","triggerScenarios":"createUserKey(userId, ...) or listUserKeys(userId, ...) called with a userId that has no row in the metadata store (deleted user, wrong id, wrong tenant/database).","commonSituations":"Using a stale user id after the user was deleted, passing an id from a different environment (prod id against dev DB), copy-paste of a truncated or wrong-kind identifier, or users created outside this metadata store.","solutions":["Verify the userId exists (query the users table / getUserById) before creating or listing keys.","Re-fetch the correct user id — the record may have been deleted or the id may come from the wrong environment.","Confirm the service is pointed at the same database/tenant where the user was created.","Catch MetadataError with code 'user_not_found' and return a 404-style response to the API caller."],"exampleFix":"// before\nawait metadataService.createUserKey(unknownId, { name: \"key\" });\n// after — check existence first\nconst user = await metadataService.getUserById(unknownId);\nif (!user) throw new NotFoundError(`user not found: ${unknownId}`);\nawait metadataService.createUserKey(unknownId, { name: \"key\" });","handlingStrategy":"try-catch","validationCode":"const user = await metadataService.getUserById(userId);\nif (!user) throw new NotFoundError(`user not found: ${userId}`);\nawait metadataService.createUserKey(userId, keySpec);","typeGuard":null,"tryCatchPattern":"try {\n  keys = await metadataService.listUserKeys(userId, pagination);\n} catch (e) {\n  if (e instanceof MetadataError && e.code === \"user_not_found\") {\n    return res.status(404).json({ error: `user ${userId} does not exist` });\n  }\n  throw e;\n}","preventionTips":["Confirm user creation succeeded and capture the returned id rather than constructing ids by hand.","Sanity-check environment: don't use ids across dev/staging/prod databases.","Handle cascading deletes: when a user is removed, clean up or short-circuit dependent key flows.","Map user_not_found to HTTP 404 at the API layer with a clear message."],"tags":["user","not-found","lookup"],"backgroundTag":"user-not-found","analyzedSha":"3efcd317b84146d6a08518ac0f7ee7c8a8d200ec","analyzedAt":"2026-09-01T05:44:22.276Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-08T10:18:20.063Z"}