refactor(errors): classify auth and browser failures

This commit is contained in:
2026-07-03 13:20:16 +08:00
parent 8a71041b5d
commit 8a586e4471
7 changed files with 177 additions and 9 deletions
@@ -69,7 +69,11 @@ async function refreshLoginToken(baseUrl: string): Promise<void> {
const storage = AuthStorage.getInstance();
const refreshResult = await storage.getRefreshToken();
if (!Result.isOk(refreshResult) || !refreshResult.data) {
throw new Error("No refresh token available");
throw new ApiError(
"HTTP_UNAUTHORIZED",
"No refresh token available",
ErrorCode.httpUnauthorized,
);
}
const response = await fetch(`${baseUrl}${ApiPath.refresh}`, {
@@ -79,7 +83,12 @@ async function refreshLoginToken(baseUrl: string): Promise<void> {
});
if (!response.ok) {
throw new Error(`Refresh failed: ${response.status}`);
throw new ApiError(
apiCodeForStatus(response.status),
"Refresh failed",
response.status,
{ statusText: response.statusText },
);
}
const json = (await response.json()) as {
@@ -91,7 +100,7 @@ async function refreshLoginToken(baseUrl: string): Promise<void> {
if (json.data.token) await storage.setLoginToken(json.data.token);
if (json.data.refreshToken) await storage.setRefreshToken(json.data.refreshToken);
} else {
throw new Error("Refresh response invalid");
throw new ApiError(ErrorCode.parseError, "Refresh response invalid");
}
}
@@ -109,7 +118,12 @@ async function refreshGuestToken(baseUrl: string): Promise<void> {
});
if (!response.ok) {
throw new Error(`Guest refresh failed: ${response.status}`);
throw new ApiError(
apiCodeForStatus(response.status),
"Guest refresh failed",
response.status,
{ statusText: response.statusText },
);
}
const json = (await response.json()) as {
@@ -121,7 +135,22 @@ async function refreshGuestToken(baseUrl: string): Promise<void> {
if (json.data.token) await storage.setGuestToken(json.data.token);
if (json.data.deviceId) await storage.setDeviceId(json.data.deviceId);
} else {
throw new Error("Guest refresh response invalid");
throw new ApiError(ErrorCode.parseError, "Guest refresh response invalid");
}
}
function apiCodeForStatus(status: number): string {
switch (status) {
case ErrorCode.httpUnauthorized:
return "HTTP_UNAUTHORIZED";
case ErrorCode.httpForbidden:
return "HTTP_FORBIDDEN";
case ErrorCode.httpNotFound:
return "HTTP_NOT_FOUND";
case ErrorCode.httpServerError:
return "HTTP_SERVER_ERROR";
default:
return "HTTP_ERROR";
}
}