From 69c800fbb6b6636a2f225fb1ffba5b1a43338b5e Mon Sep 17 00:00:00 2001 From: npmrun <1549469775@qq.com> Date: Fri, 15 May 2026 14:31:18 +0800 Subject: [PATCH] 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 --- server/api/auth/register.post.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/server/api/auth/register.post.ts b/server/api/auth/register.post.ts index 7f86f1a..4d420a6 100644 --- a/server/api/auth/register.post.ts +++ b/server/api/auth/register.post.ts @@ -2,8 +2,10 @@ import { registerSchema } from '../../utils/auth/validation' import { verifyCaptcha } from '../../utils/auth/captcha' import { dbGlobal } from 'drizzle-pkg/lib/db' import { users } from 'drizzle-pkg/lib/schema/auth' - import { hash } from 'bcryptjs' +import log4js from 'logger' + +const logger = log4js.getLogger('AUTH') export default defineWrappedResponseHandler(async (event) => { const body = await readBody(event) @@ -33,7 +35,12 @@ export default defineWrappedResponseHandler(async (event) => { .returning({ id: users.id }) return R.success({ id: result[0].id, username }) - } catch { - return R.error('用户名已存在', null) + } catch (err: any) { + const msg = String(err?.message ?? '') + if (msg.toLowerCase().includes('unique') || msg.includes('SQLITE_CONSTRAINT')) { + return R.error('用户名已存在', null) + } + logger.error('Failed to insert user', msg) + return R.error('注册失败,请稍后重试', null) } })