Browse Source

fix: differentiate UNIQUE constraint from other DB errors on registration

Previously the catch block treated all insert errors as "username already
exists". Now it checks the error message for UNIQUE/SQLITE_CONSTRAINT and
only returns the duplicate-username message for that case. Other errors
are logged and return a generic failure message.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
feat/registration-page
npmrun 2 weeks ago
parent
commit
69c800fbb6
  1. 11
      server/api/auth/register.post.ts

11
server/api/auth/register.post.ts

@ -2,8 +2,10 @@ import { registerSchema } from '../../utils/auth/validation'
import { verifyCaptcha } from '../../utils/auth/captcha' import { verifyCaptcha } from '../../utils/auth/captcha'
import { dbGlobal } from 'drizzle-pkg/lib/db' import { dbGlobal } from 'drizzle-pkg/lib/db'
import { users } from 'drizzle-pkg/lib/schema/auth' import { users } from 'drizzle-pkg/lib/schema/auth'
import { hash } from 'bcryptjs' import { hash } from 'bcryptjs'
import log4js from 'logger'
const logger = log4js.getLogger('AUTH')
export default defineWrappedResponseHandler(async (event) => { export default defineWrappedResponseHandler(async (event) => {
const body = await readBody(event) const body = await readBody(event)
@ -33,7 +35,12 @@ export default defineWrappedResponseHandler(async (event) => {
.returning({ id: users.id }) .returning({ id: users.id })
return R.success({ id: result[0].id, username }) return R.success({ id: result[0].id, username })
} catch { } catch (err: any) {
const msg = String(err?.message ?? '')
if (msg.toLowerCase().includes('unique') || msg.includes('SQLITE_CONSTRAINT')) {
return R.error('用户名已存在', null) return R.error('用户名已存在', null)
} }
logger.error('Failed to insert user', msg)
return R.error('注册失败,请稍后重试', null)
}
}) })

Loading…
Cancel
Save