This commit is contained in:
eric
2026-03-12 04:25:12 -05:00
parent 528044db7d
commit 39a8358af1
7 changed files with 190 additions and 12 deletions

View File

@@ -39,6 +39,31 @@ export async function pbLogin(
return { token: data.token, record: data.record };
}
/** 从 PocketBase 错误响应中提取可读错误信息 */
function parsePBError(err: { message?: string; data?: Record<string, { message?: string; code?: string }> }): string {
const data = err?.data;
if (data && typeof data === "object" && Object.keys(data).length > 0) {
const first = Object.values(data)[0];
if (first?.message) {
const code = first.code;
if (code === "validation_not_unique") {
return "该邮箱已被注册,请直接登录";
}
if (code === "validation_required") {
return "请填写必填项";
}
if (code?.startsWith("validation_")) {
return first.message;
}
return first.message;
}
}
if (err?.message === "Failed to create record.") {
return "注册失败,该邮箱可能已被使用,请尝试直接登录";
}
return err?.message || "注册失败";
}
export async function pbRegister(
email: string,
password: string,
@@ -51,8 +76,8 @@ export async function pbRegister(
body: JSON.stringify({ email, password, passwordConfirm }),
});
if (!res.ok) {
const err = await res.json();
throw new Error(err?.message || "注册失败");
const err = await res.json().catch(() => ({}));
throw new Error(parsePBError(err));
}
return pbLogin(email, password);
}
@@ -69,7 +94,7 @@ export async function pbLogout(): Promise<void> {
localStorage.removeItem(PB_STORAGE_KEYS.token);
localStorage.removeItem(PB_STORAGE_KEYS.user);
try {
await fetch("/api/auth/logout", { method: "POST" });
await fetch("/api/auth/logout", { method: "POST", credentials: "include" });
} catch {
/* ignore */
}