Browse Source

🐛 fix(auth): 添加登录错误处理逻辑

- 增加try/catch块捕获登录过程中的异常
- 针对用户不存在和密码错误返回401状态码和友好提示
- 统一认证错误信息为"用户名或密码错误"
- 保留其他错误由全局错误处理中间件处理
- 添加500状态码的API文档描述
yourname 2 months ago
parent
commit
99c7b28f4f
1 changed files with 28 additions and 3 deletions
  1. 28 3
      src/server/api/auth/login/password.ts

+ 28 - 3
src/server/api/auth/login/password.ts

@@ -59,13 +59,38 @@ const loginRoute = createRoute({
           schema: ErrorSchema
         }
       }
+    },
+    500: {
+      description: '服务器内部错误',
+      content: {
+        'application/json': {
+          schema: ErrorSchema
+        }
+      }
     }
   }
 })
 const app = new OpenAPIHono<AuthContext>().openapi(loginRoute, async (c) => {
-  const { username, password } = c.req.valid('json')
-  const result = await authService.login(username, password)
-  return c.json(result, 200)
+  try {
+    const { username, password } = c.req.valid('json')
+    const result = await authService.login(username, password)
+    return c.json(result, 200)
+  } catch (error) {
+    // 认证相关错误返回401
+    if (error instanceof Error &&
+        (error.message.includes('User not found') || error.message.includes('Invalid password'))) {
+      return c.json(
+        {
+          code: 401,
+          message: '用户名或密码错误'
+        },
+        401
+      )
+    }
+
+    // 其他错误重新抛出,由错误处理中间件处理
+    throw error
+  }
 });
 
 export default app