fix: better error handling for public key constraint

- Add try/catch in claimUsername to handle UNIQUE constraint
- Return meaningful error: 'This public key has already claimed a different username'
- Enable observability logs for better debugging
This commit is contained in:
2025-12-08 21:31:36 +01:00
parent 163e1f73d4
commit b446adaee4
2 changed files with 37 additions and 29 deletions

View File

@@ -320,6 +320,7 @@ export class D1Storage implements Storage {
const now = Date.now(); const now = Date.now();
const expiresAt = now + YEAR_IN_MS; const expiresAt = now + YEAR_IN_MS;
try {
// Try to insert or update // Try to insert or update
const result = await this.db.prepare(` const result = await this.db.prepare(`
INSERT INTO usernames (username, public_key, claimed_at, expires_at, last_used, metadata) INSERT INTO usernames (username, public_key, claimed_at, expires_at, last_used, metadata)
@@ -350,6 +351,13 @@ export class D1Storage implements Storage {
expiresAt, expiresAt,
lastUsed: now, lastUsed: now,
}; };
} catch (err: any) {
// Handle UNIQUE constraint on public_key
if (err.message?.includes('UNIQUE constraint failed: usernames.public_key')) {
throw new Error('This public key has already claimed a different username');
}
throw err;
}
} }
async getUsername(username: string): Promise<Username | null> { async getUsername(username: string): Promise<Username | null> {

View File

@@ -39,7 +39,7 @@ command = ""
[observability] [observability]
[observability.logs] [observability.logs]
enabled = false enabled = true
head_sampling_rate = 1 head_sampling_rate = 1
invocation_logs = true invocation_logs = true
persist = true persist = true