Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

update handling of httpService error using ApiError

Abhinavc119a5f714e7
diff --git a/apps/photos/src/pages/deduplicate/index.tsx b/apps/photos/src/pages/deduplicate/index.tsx
index a611ae673c..b6405078cd 100644
--- a/apps/photos/src/pages/deduplicate/index.tsx
+++ b/apps/photos/src/pages/deduplicate/index.tsx
@@ -12,7 +12,7 @@ import { syncFiles, trashFiles } from 'services/fileService';
import { EnteFile } from 'types/file';
import { SelectedState } from 'types/gallery';
-import { ServerErrorCodes } from 'utils/error';
+import { ApiError } from 'utils/error';
import { constructFileToCollectionMap, getSelectedFiles } from 'utils/file';
import {
DeduplicateContextType,
@@ -30,6 +30,7 @@ import { VerticallyCentered } from 'components/Container';
import Typography from '@mui/material/Typography';
import useMemoSingleThreaded from 'hooks/useMemoSingleThreaded';
import InMemoryStore, { MS_KEYS } from 'services/InMemoryStore';
+import { HttpStatusCode } from 'axios';
export const DeduplicateContext = createContext<DeduplicateContextType>(
DefaultDeduplicateContext
@@ -124,21 +125,24 @@ export default function Deduplicate() {
const selectedFiles = getSelectedFiles(selected, duplicateFiles);
await trashFiles(selectedFiles);
} catch (e) {
- switch (e.status?.toString()) {
- case ServerErrorCodes.FORBIDDEN:
- setDialogMessage({
- title: t('ERROR'),
+ if (
+ e instanceof ApiError &&
+ e.httpStatusCode === HttpStatusCode.Forbidden
+ ) {
+ setDialogMessage({
+ title: t('ERROR'),
- close: { variant: 'critical' },
- content: t('NOT_FILE_OWNER'),
- });
- }
- setDialogMessage({
- title: t('ERROR'),
+ close: { variant: 'critical' },
+ content: t('NOT_FILE_OWNER'),
+ });
+ } else {
+ setDialogMessage({
+ title: t('ERROR'),
- close: { variant: 'critical' },
- content: t('UNKNOWN_ERROR'),
- });
+ close: { variant: 'critical' },
+ content: t('UNKNOWN_ERROR'),
+ });
+ }
} finally {
await syncWithRemote();
finishLoading();
diff --git a/apps/photos/src/pages/gallery/index.tsx b/apps/photos/src/pages/gallery/index.tsx
index e308301cd5..29d275eeb0 100644
--- a/apps/photos/src/pages/gallery/index.tsx
+++ b/apps/photos/src/pages/gallery/index.tsx
@@ -70,7 +70,7 @@ import {
TRASH_SECTION,
} from 'constants/collection';
import { AppContext } from 'pages/_app';
-import { CustomError, ServerErrorCodes } from 'utils/error';
+import { CustomError } from 'utils/error';
import { PAGES } from 'constants/pages';
import {
COLLECTION_OPS_TYPE,
@@ -679,7 +679,7 @@ export default function Gallery() {
}
const tokenValid = await isTokenValid(token);
if (!tokenValid) {
- throw new Error(ServerErrorCodes.SESSION_EXPIRED);
+ throw new Error(CustomError.SESSION_EXPIRED);
}
!silent && startLoading();
const collections = await getAllLatestCollections();
@@ -694,7 +694,7 @@ export default function Gallery() {
await syncMapEnabled();
} catch (e) {
switch (e.message) {
- case ServerErrorCodes.SESSION_EXPIRED:
+ case CustomError.SESSION_EXPIRED:
showSessionExpiredMessage();
break;
case CustomError.KEY_MISSING:
diff --git a/apps/photos/src/pages/two-factor/recover/index.tsx b/apps/photos/src/pages/two-factor/recover/index.tsx
index 9c9f0d12e9..b16cf2a65d 100644
--- a/apps/photos/src/pages/two-factor/recover/index.tsx
+++ b/apps/photos/src/pages/two-factor/recover/index.tsx
@@ -24,6 +24,8 @@ import { Trans } from 'react-i18next';
import { Link } from '@mui/material';
import { SUPPORT_EMAIL } from 'constants/urls';
import { DialogBoxAttributes } from 'types/dialogBox';
+import { ApiError } from 'utils/error';
+import { HttpStatusCode } from 'axios';
const bip39 = require('bip39');
// mobile client library only supports english.
@@ -68,7 +70,10 @@ export default function Recover() {
});
}
} catch (e) {
- if (e.status === 404) {
+ if (
+ e instanceof ApiError &&
+ e.httpStatusCode === HttpStatusCode.NotFound
+ ) {
logoutUser();
} else {
logError(e, 'two factor recovery page setup failed');
diff --git a/apps/photos/src/pages/two-factor/verify/index.tsx b/apps/photos/src/pages/two-factor/verify/index.tsx
index 85cb0b4708..e05fd7d85e 100644
--- a/apps/photos/src/pages/two-factor/verify/index.tsx
+++ b/apps/photos/src/pages/two-factor/verify/index.tsx
@@ -15,6 +15,8 @@ import FormTitle from 'components/Form/FormPaper/Title';
import FormPaperFooter from 'components/Form/FormPaper/Footer';
import { VerticallyCentered } from 'components/Container';
import InMemoryStore, { MS_KEYS } from 'services/InMemoryStore';
+import { ApiError } from 'utils/error';
+import { HttpStatusCode } from 'axios';
export default function Home() {
const [sessionID, setSessionID] = useState('');
@@ -52,11 +54,13 @@ export default function Home() {
InMemoryStore.delete(MS_KEYS.REDIRECT_URL);
router.push(redirectURL ?? PAGES.CREDENTIALS);
} catch (e) {
- if (e.status === 404) {
- logoutUser();
- } else {
- throw e;
+ if (e instanceof ApiError) {
+ if (e.httpStatusCode === HttpStatusCode.NotFound) {
+ logoutUser();
+ return;
+ }
}
+ throw e;
}
};
return (
diff --git a/apps/photos/src/pages/verify/index.tsx b/apps/photos/src/pages/verify/index.tsx
index 8de5b2e89b..b41684dac9 100644
--- a/apps/photos/src/pages/verify/index.tsx
+++ b/apps/photos/src/pages/verify/index.tsx
@@ -33,6 +33,8 @@ import SingleInputForm, {
import EnteSpinner from 'components/EnteSpinner';
import { VerticallyCentered } from 'components/Container';
import InMemoryStore, { MS_KEYS } from 'services/InMemoryStore';
+import { ApiError } from 'utils/error';
+import { HttpStatusCode } from 'axios';
export default function Verify() {
const [email, setEmail] = useState('');
@@ -122,13 +124,14 @@ export default function Verify() {
}
}
} catch (e) {
- if (e?.status === 401) {
- setFieldError(t('INVALID_CODE'));
- } else if (e?.status === 410) {
- setFieldError(t('EXPIRED_CODE'));
- } else {
- setFieldError(`${t('UNKNOWN_ERROR')} ${e.message}`);
+ if (e instanceof ApiError) {
+ if (e?.httpStatusCode === HttpStatusCode.Unauthorized) {
+ setFieldError(t('INVALID_CODE'));
+ } else if (e?.httpStatusCode === HttpStatusCode.Gone) {
+ setFieldError(t('EXPIRED_CODE'));
+ }
}
+ setFieldError(`${t('UNKNOWN_ERROR')} ${e.message}`);
}
};
diff --git a/apps/photos/src/services/HTTPService.ts b/apps/photos/src/services/HTTPService.ts
index e3c023df37..dae21d1161 100644
--- a/apps/photos/src/services/HTTPService.ts
+++ b/apps/photos/src/services/HTTPService.ts
@@ -33,7 +33,7 @@ class HTTPService {
url: config.url,
method: config.method,
xRequestId: response.headers['x-request-id'],
- httpStatusCode: response.status,
+ httpStatus: response.status,
errMessage: apiError.message,
errCode: apiError.errCode,
});
@@ -49,19 +49,19 @@ class HTTPService {
method: config.method,
cfRay: response.headers['cf-ray'],
xRequestId: response.headers['x-request-id'],
- status: response.status,
+ httpStatus: response.status,
});
if (response.status >= 400 && response.status < 500) {
throw new ApiError(
CustomError.CLIENT_ERROR,
- response.status.toString(),
+ '',
response.status,
response.statusText
);
} else {
throw new ApiError(
CustomError.ServerError,
- response.status.toString(),
+ '',
response.status,
response.statusText
);
diff --git a/apps/photos/src/services/authenticator/authenticatorService.ts b/apps/photos/src/services/authenticator/authenticatorService.ts
index 686bc7e45b..c618e12b21 100644
--- a/apps/photos/src/services/authenticator/authenticatorService.ts
+++ b/apps/photos/src/services/authenticator/authenticatorService.ts
@@ -1,10 +1,11 @@
+import { HttpStatusCode } from 'axios';
import HTTPService from 'services/HTTPService';
import { AuthEntity, AuthKey } from 'types/authenticator/api';
import { Code } from 'types/authenticator/code';
import ComlinkCryptoWorker from 'utils/comlink/ComlinkCryptoWorker';
import { getEndpoint } from 'utils/common/apiUtil';
import { getActualKey, getToken } from 'utils/common/key';
-import { CustomError } from 'utils/error';
+import { ApiError, CustomError } from 'utils/error';
import { logError } from 'utils/sentry';
const ENDPOINT = getEndpoint();
@@ -77,12 +78,13 @@ export const getAuthKey = async (): Promise<AuthKey> => {
);
return resp.data;
} catch (e) {
- if (e.status === 404) {
- throw Error(CustomError.AUTH_KEY_NOT_FOUND);
- } else {
- logError(e, 'Get key failed');
- throw e;
+ logError(e, 'Get key failed');
+ if (e instanceof ApiError) {
+ if (e.httpStatusCode === HttpStatusCode.NotFound) {
+ throw Error(CustomError.AUTH_KEY_NOT_FOUND);
+ }
}
+ throw e;
}
};
diff --git a/apps/photos/src/services/userService.ts b/apps/photos/src/services/userService.ts
index 88c39b3a44..3c4b764c77 100644
--- a/apps/photos/src/services/userService.ts
+++ b/apps/photos/src/services/userService.ts
@@ -40,13 +40,13 @@ import {
UpdateSRPAndKeysResponse,
GetSRPAttributesResponse,
} from 'types/user';
-import { ServerErrorCodes } from 'utils/error';
+import { ApiError, CustomError } from 'utils/error';
import isElectron from 'is-electron';
import safeStorageService from './electron/safeStorage';
import { deleteAllCache } from 'utils/storage/cache';
import { B64EncryptionResult } from 'types/crypto';
import { getLocalFamilyData, isPartOfFamily } from 'utils/user/family';
-import { AxiosResponse } from 'axios';
+import { AxiosResponse, HttpStatusCode } from 'axios';
import { APPS, getAppName } from 'constants/apps';
import { addLocalLog } from 'utils/logging';
import { convertBase64ToBuffer, convertBufferToBase64 } from 'utils/user';
@@ -224,10 +224,12 @@ export const isTokenValid = async (token: string) => {
return true;
} catch (e) {
logError(e, 'session-validity api call failed');
- if (e.status?.toString() === ServerErrorCodes.SESSION_EXPIRED) {
- return false;
- } else {
- return true;
+ if (e instanceof ApiError) {
+ if (e.httpStatusCode === HttpStatusCode.Unauthorized) {
+ return false;
+ } else {
+ return true;
+ }
}
}
};
@@ -727,6 +729,11 @@ export const verifySRPSession = async (
return resp.data as UserVerificationResponse;
} catch (e) {
logError(e, 'verifySRPSession failed');
+ if (e instanceof ApiError) {
+ if (e.httpStatusCode === HttpStatusCode.Unauthorized) {
+ throw Error(CustomError.INCORRECT_PASSWORD);
+ }
+ }
throw e;
}
};
diff --git a/apps/photos/src/utils/error/index.ts b/apps/photos/src/utils/error/index.ts
index 053a982aa2..71c7924884 100644
--- a/apps/photos/src/utils/error/index.ts
+++ b/apps/photos/src/utils/error/index.ts
@@ -1,5 +1,7 @@
+import { HttpStatusCode } from 'axios';
+
export class ApiError extends Error {
- httpStatus: number;
+ httpStatusCode: number;
httpStatusText: string;
errCode: string;
@@ -12,7 +14,7 @@ export class ApiError extends Error {
super(message);
this.name = 'ApiError';
this.errCode = errCode;
- this.httpStatus = httpStatus;
+ this.httpStatusCode = httpStatus;
this.httpStatusText = httpStatusText;
}
}
@@ -21,19 +23,6 @@ export function isApiError(object: any): object is ApiError {
return object && 'code' in object && 'message' in object;
}
-export const ServerErrorCodes = {
- SESSION_EXPIRED: '401',
- NO_ACTIVE_SUBSCRIPTION: '402',
- FORBIDDEN: '403',
- STORAGE_LIMIT_EXCEEDED: '426',
- FILE_TOO_LARGE: '413',
- TOKEN_EXPIRED: '410',
- TOO_MANY_REQUEST: '429',
- BAD_REQUEST: '400',
- PAYMENT_REQUIRED: '402',
- NOT_FOUND: '404',
-};
-
export const CustomError = {
THUMBNAIL_GENERATION_FAILED: 'thumbnail generation failed',
VIDEO_PLAYBACK_FAILED: 'video playback failed',
@@ -99,32 +88,6 @@ export const CustomError = {
ServerError: 'server error',
};
-export function parseUploadErrorCodes(error) {
- let parsedMessage = null;
- if (error?.status) {
- const errorCode = error.status.toString();
- switch (errorCode) {
- case ServerErrorCodes.NO_ACTIVE_SUBSCRIPTION:
- parsedMessage = CustomError.SUBSCRIPTION_EXPIRED;
- break;
- case ServerErrorCodes.STORAGE_LIMIT_EXCEEDED:
- parsedMessage = CustomError.STORAGE_QUOTA_EXCEEDED;
- break;
- case ServerErrorCodes.SESSION_EXPIRED:
- parsedMessage = CustomError.SESSION_EXPIRED;
- break;
- case ServerErrorCodes.FILE_TOO_LARGE:
- parsedMessage = CustomError.FILE_TOO_LARGE;
- break;
- default:
- parsedMessage = `${CustomError.UNKNOWN_ERROR} statusCode:${errorCode}`;
- }
- } else {
- parsedMessage = error.message;
- }
- return new Error(parsedMessage);
-}
-
export function handleUploadError(error): Error {
const parsedError = parseUploadErrorCodes(error);
@@ -148,29 +111,53 @@ export function errorWithContext(originalError: Error, context: string) {
return errorWithContext;
}
+export function parseUploadErrorCodes(error) {
+ let parsedMessage = null;
+ if (error instanceof ApiError) {
+ switch (error.httpStatusCode) {
+ case HttpStatusCode.PaymentRequired:
+ parsedMessage = CustomError.SUBSCRIPTION_EXPIRED;
+ break;
+ case HttpStatusCode.UpgradeRequired:
+ parsedMessage = CustomError.STORAGE_QUOTA_EXCEEDED;
+ break;
+ case HttpStatusCode.Unauthorized:
+ parsedMessage = CustomError.SESSION_EXPIRED;
+ break;
+ case HttpStatusCode.PayloadTooLarge:
+ parsedMessage = CustomError.FILE_TOO_LARGE;
+ break;
+ default:
+ parsedMessage = `${CustomError.UNKNOWN_ERROR} statusCode:${error.httpStatusCode}`;
+ }
+ } else {
+ parsedMessage = error.message;
+ }
+ return new Error(parsedMessage);
+}
+
export const parseSharingErrorCodes = (error) => {
let parsedMessage = null;
- if (error?.status) {
- const errorCode = error.status.toString();
- switch (errorCode) {
- case ServerErrorCodes.BAD_REQUEST:
+ if (error instanceof ApiError) {
+ switch (error.httpStatusCode) {
+ case HttpStatusCode.BadRequest:
parsedMessage = CustomError.BAD_REQUEST;
break;
- case ServerErrorCodes.PAYMENT_REQUIRED:
+ case HttpStatusCode.PaymentRequired:
parsedMessage = CustomError.SUBSCRIPTION_NEEDED;
break;
- case ServerErrorCodes.NOT_FOUND:
+ case HttpStatusCode.NotFound:
parsedMessage = CustomError.NOT_FOUND;
break;
- case ServerErrorCodes.SESSION_EXPIRED:
- case ServerErrorCodes.TOKEN_EXPIRED:
+ case HttpStatusCode.Unauthorized:
+ case HttpStatusCode.Gone:
parsedMessage = CustomError.TOKEN_EXPIRED;
break;
- case ServerErrorCodes.TOO_MANY_REQUEST:
+ case HttpStatusCode.TooManyRequests:
parsedMessage = CustomError.TOO_MANY_REQUESTS;
break;
default:
- parsedMessage = `${CustomError.UNKNOWN_ERROR} statusCode:${errorCode}`;
+ parsedMessage = `${CustomError.UNKNOWN_ERROR} statusCode:${error.httpStatusCode}`;
}
} else {
parsedMessage = error.message;
diff --git a/apps/photos/src/utils/sentry/index.ts b/apps/photos/src/utils/sentry/index.ts
index 90cea09047..e566309056 100644
--- a/apps/photos/src/utils/sentry/index.ts
+++ b/apps/photos/src/utils/sentry/index.ts
@@ -17,7 +17,7 @@ export const logError = async (
addLogLine(`
error: ${error?.name} ${error?.message} ${error?.stack}
msg: ${msg} errorCode: ${JSON.stringify(error?.errCode)}
- httpCode: ${JSON.stringify(error?.httpStatus)} ${
+ httpStatusCode: ${JSON.stringify(error?.httpStatusCode)} ${
info ? `info: ${JSON.stringify(info)}` : ''
}`);
} else {
@@ -39,9 +39,6 @@ export const logError = async (
addLocalLog(() => `skipping sentry error: ${error?.name}`);
return;
}
- if (isErrorUnnecessaryForSentry(error)) {
- return;
- }
Sentry.captureException(err, {
level: 'info',
@@ -64,12 +61,3 @@ function errorWithContext(originalError: Error, context: string) {
originalError.stack;
return errorWithContext;
}
-
-function isErrorUnnecessaryForSentry(error: any) {
- if (error?.message?.includes('Network Error')) {
- return true;
- } else if (error?.status === 401) {
- return true;
- }
- return false;
-}