Skip to content

Commit

Permalink
Merge pull request #9671 from DestinyItemManager/useUnknownInCatchVar…
Browse files Browse the repository at this point in the history
…iables
  • Loading branch information
bhollis authored Jul 27, 2023
2 parents ac65b01 + e544190 commit 7a1ce26
Show file tree
Hide file tree
Showing 44 changed files with 234 additions and 175 deletions.
15 changes: 3 additions & 12 deletions src/StorageTest.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { t } from 'app/i18next-t';
import ErrorPanel from 'app/shell/ErrorPanel';
import { deleteDatabase, set } from 'app/storage/idb-keyval';
import { reportException } from 'app/utils/exceptions';
import { set } from 'app/storage/idb-keyval';
import { errorLog } from 'app/utils/log';

export function StorageBroken() {
Expand Down Expand Up @@ -32,16 +31,8 @@ export async function storageTest() {
try {
await set('idb-test', true);
} catch (e) {
errorLog('storage', 'Failed IndexedDB Test - trying to delete database', e);
try {
await deleteDatabase();
await set('idb-test', true);
// Report to sentry, I want to know if this ever works
reportException('deleting database fixed IDB', e);
} catch (e2) {
errorLog('storage', 'Failed IndexedDB Test - deleting database did not help', e);
return false;
}
errorLog('storage', 'Failed IndexedDB Test', e);
return false;
}

return true;
Expand Down
2 changes: 1 addition & 1 deletion src/app/accounts/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export const needsDeveloper = createAction('accounts/DEV_INFO_NEEDED')();
/**
* Inspect an error and potentially log out the user or send them to the developer page
*/
export function handleAuthErrors(e: Error): ThunkResult {
export function handleAuthErrors(e: unknown): ThunkResult {
return async (dispatch) => {
// This means we don't have an API key or the API key is wrong
if ($DIM_FLAVOR === 'dev' && e instanceof DimError && e.code === 'BungieService.DevVersion') {
Expand Down
4 changes: 2 additions & 2 deletions src/app/accounts/platforms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { deleteDimApiToken } from 'app/dim-api/dim-api-helper';
import { del, get } from 'app/storage/idb-keyval';
import { ThunkResult } from 'app/store/types';
import { errorLog } from 'app/utils/log';
import { dedupePromise } from 'app/utils/util';
import { convertToError, dedupePromise } from 'app/utils/util';
import { removeToken } from '../bungie-api/oauth-tokens';
import { loadingTracker } from '../shell/loading-tracker';
import * as actions from './actions';
Expand Down Expand Up @@ -40,7 +40,7 @@ const getPlatformsAction: ThunkResult = dedupePromise(async (dispatch, getState)
try {
await realAccountsPromise;
} catch (e) {
dispatch(actions.error(e));
dispatch(actions.error(convertToError(e)));
errorLog('accounts', 'Unable to load accounts from Bungie.net', e);
}
}
Expand Down
8 changes: 3 additions & 5 deletions src/app/bungie-api/authenticated-fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ export async function fetchWithBungieOAuth(
const token = await getActiveToken();
request.headers.set('Authorization', `Bearer ${token.accessToken.value}`);
} catch (e) {
// Note: instanceof doesn't work due to a babel bug:
if (e.name === 'FatalTokenError') {
if (e instanceof FatalTokenError) {
warnLog('bungie auth', 'Unable to get auth token', e);
}
throw e;
Expand Down Expand Up @@ -103,7 +102,7 @@ export async function getActiveToken(): Promise<Tokens> {
}
}

async function handleRefreshTokenError(response: Error | Response): Promise<Tokens> {
async function handleRefreshTokenError(response: unknown): Promise<Tokens> {
if (response instanceof TypeError) {
warnLog(
'bungie auth',
Expand All @@ -112,15 +111,14 @@ async function handleRefreshTokenError(response: Error | Response): Promise<Toke
);
throw response;
}
if (response instanceof Error) {
if (!(response instanceof Response)) {
warnLog(
'bungie auth',
'Other error getting auth token from refresh token. Not clearing auth tokens',
response
);
throw response;
}

let data;
try {
data = await response.json();
Expand Down
13 changes: 6 additions & 7 deletions src/app/bungie-api/bungie-service-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ function dimErrorHandledHttpClient(httpClient: HttpClient): HttpClient {
/**
* if HttpClient throws an error (js, Bungie, http) this enriches it with DIM concepts and then re-throws it
*/
function handleErrors(error: Error) {
function handleErrors(error: unknown) {
if (error instanceof DOMException && error.name === 'AbortError') {
throw (
navigator.onLine
Expand Down Expand Up @@ -212,12 +212,11 @@ function handleErrors(error: Error) {
}

// Handle "DestinyUniquenessViolation" (1648)
export function handleUniquenessViolation(
error: BungieError,
item: DimItem,
store: DimStore
): never {
if (error?.code === PlatformErrorCodes.DestinyUniquenessViolation) {
export function handleUniquenessViolation(error: unknown, item: DimItem, store: DimStore): never {
if (
error instanceof BungieError &&
error.code === PlatformErrorCodes.DestinyUniquenessViolation
) {
throw new DimError(
'BungieService.ItemUniquenessExplanation',
t('BungieService.ItemUniquenessExplanation', {
Expand Down
8 changes: 4 additions & 4 deletions src/app/bungie-api/error-toaster.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,13 @@ import { AppIcon, twitterIcon } from '../shell/icons';
*
* Use this for when you suspect Bungie.net is down.
*/
export function bungieErrorToaster(e: Error): NotifyInput {
export function bungieErrorToaster(errorMessage: string | undefined): NotifyInput {
return {
type: 'error',
title: t('BungieService.ErrorTitle'),
body: (
<>
{e ? e.message : t('BungieService.Difficulties')}{' '}
{errorMessage ?? t('BungieService.Difficulties')}{' '}
<div>
{t('BungieService.Twitter')}{' '}
<ExternalLink href={bungieHelpLink}>{bungieTwitterAccount}</ExternalLink>{' '}
Expand All @@ -30,14 +30,14 @@ export function bungieErrorToaster(e: Error): NotifyInput {
};
}

export function dimErrorToaster(title: string, message: string, e: Error): NotifyInput {
export function dimErrorToaster(title: string, message: string, errorMessage: string): NotifyInput {
return {
type: 'error',
title,
body: (
<>
<div>{message}</div>
<div>{e.message}</div>
<div>{errorMessage}</div>
</>
),
duration: 60_000,
Expand Down
4 changes: 2 additions & 2 deletions src/app/bungie-api/http-client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { delay } from 'app/utils/util';
import { convertToError, delay } from 'app/utils/util';
import { PlatformErrorCodes, ServerResponse } from 'bungie-api-ts/destiny2';
import { HttpClient, HttpClientConfig } from 'bungie-api-ts/http';

Expand Down Expand Up @@ -172,7 +172,7 @@ export function createHttpClient(fetchFunction: typeof fetch, apiKey: string): H
try {
data = await response.json();
} catch (e) {
parseError = e;
parseError = convertToError(e);
}
// try throwing bungie errors, which have more information, first
throwBungieError(data, fetchOptions);
Expand Down
62 changes: 31 additions & 31 deletions src/app/bungie-api/oauth.ts
Original file line number Diff line number Diff line change
@@ -1,59 +1,59 @@
import { infoLog } from 'app/utils/log';
import { dedupePromise } from 'app/utils/util';
import { oauthClientId, oauthClientSecret } from './bungie-api-utils';
import { HttpStatusError } from './http-client';
import { Token, Tokens, setToken } from './oauth-tokens';

// all these api url params don't match our variable naming conventions

const TOKEN_URL = 'https://www.bungie.net/platform/app/oauth/token/';

export const getAccessTokenFromRefreshToken = dedupePromise(
(refreshToken: Token): Promise<Tokens> => {
async (refreshToken: Token): Promise<Tokens> => {
const body = new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: refreshToken.value,
client_id: oauthClientId(),
client_secret: oauthClientSecret(),
});
// https://github.com/zloirock/core-js/issues/178#issuecomment-192081350
// ↑ we return fetch wrapped in an extra Promise.resolve so it has proper followup methods
return Promise.resolve(
fetch(TOKEN_URL, {
method: 'POST',
body,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.then((response) => (response.ok ? response.json() : Promise.reject(response)))
.then(handleAccessToken)
.then((token) => {
setToken(token);
infoLog('bungie auth', 'Successfully updated auth token from refresh token.');
return token;
})
);
const response = await fetch(TOKEN_URL, {
method: 'POST',
body,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
if (response.ok) {
const token = handleAccessToken(await response.json());
setToken(token);
infoLog('bungie auth', 'Successfully updated auth token from refresh token.');
return token;
} else {
throw response;
}
}
);

export function getAccessTokenFromCode(code: string): Promise<Tokens> {
export async function getAccessTokenFromCode(code: string): Promise<Tokens> {
const body = new URLSearchParams({
grant_type: 'authorization_code',
code,
client_id: oauthClientId(),
client_secret: oauthClientSecret(),
});
return Promise.resolve(
fetch(TOKEN_URL, {
method: 'POST',
body,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
})
.then((response) => (response.ok ? response.json() : Promise.reject(response)))
.then(handleAccessToken)
);
const response = await fetch(TOKEN_URL, {
method: 'POST',
body,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});

if (response.ok) {
return handleAccessToken(await response.json());
} else {
throw new HttpStatusError(response);
}
}

function handleAccessToken(
Expand Down
5 changes: 3 additions & 2 deletions src/app/debug/Debug.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { set } from 'app/storage/idb-keyval';
import { useThunkDispatch } from 'app/store/thunk-dispatch';
import { DimError } from 'app/utils/dim-error';
import { usePageTitle } from 'app/utils/hooks';
import { convertToError } from 'app/utils/util';
import { wishListsLastFetchedSelector, wishListsSelector } from 'app/wishlists/selectors';
import { fetchWishList } from 'app/wishlists/wishlist-fetch';
import { useEffect, useState } from 'react';
Expand Down Expand Up @@ -62,7 +63,7 @@ export default function Debug() {
try {
await set('idb-test', true);
} catch (e) {
setIdbError(e);
setIdbError(convertToError(e));
}
})();
}, []);
Expand All @@ -71,7 +72,7 @@ export default function Debug() {
try {
localStorage.setItem('test', 'true');
} catch (e) {
setLocalStorageError(e);
setLocalStorageError(convertToError(e));
}
}, []);

Expand Down
3 changes: 2 additions & 1 deletion src/app/developer/Developer.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { registerApp } from 'app/dim-api/register-app';
import { errorMessage } from 'app/utils/util';
import React, { useState } from 'react';

const createAppUrl = 'https://www.bungie.net/en/Application/Create';
Expand Down Expand Up @@ -62,7 +63,7 @@ export default function Developer(this: never) {
setDimApiKey(app.dimApiKey);
} catch (e) {
// eslint-disable-next-line no-alert
alert(e.message);
alert(errorMessage(e));
}
};

Expand Down
19 changes: 12 additions & 7 deletions src/app/dim-api/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { refresh$ } from 'app/shell/refresh-events';
import { get, set } from 'app/storage/idb-keyval';
import { RootState, ThunkResult } from 'app/store/types';
import { errorLog, infoLog } from 'app/utils/log';
import { delay } from 'app/utils/util';
import { convertToError, delay, errorMessage } from 'app/utils/util';
import { deepEqual } from 'fast-equals';
import _ from 'lodash';
import { AnyAction } from 'redux';
Expand Down Expand Up @@ -226,11 +226,14 @@ export function loadDimApiData(forceLoad = false): ThunkResult {

// Quickly heal from being failure backoff
getProfileBackoff = Math.floor(getProfileBackoff / 2);
} catch (e) {
} catch (err) {
// Only notify error once
if (!getState().dimApi.profileLoadedError) {
showProfileLoadErrorNotification(e);
showProfileLoadErrorNotification(err);
}

const e = convertToError(err);

dispatch(profileLoadError(e));

errorLog('loadDimApiData', 'Unable to get profile from DIM API', e);
Expand Down Expand Up @@ -400,12 +403,14 @@ export function deleteAllApiData(): ThunkResult<DeleteAllResponse['deleted']> {
};
}

function showProfileLoadErrorNotification(e: Error) {
function showProfileLoadErrorNotification(e: unknown) {
showNotification(
dimErrorToaster(t('Storage.ProfileErrorTitle'), t('Storage.ProfileErrorBody'), e)
dimErrorToaster(t('Storage.ProfileErrorTitle'), t('Storage.ProfileErrorBody'), errorMessage(e))
);
}

function showUpdateErrorNotification(e: Error) {
showNotification(dimErrorToaster(t('Storage.UpdateErrorTitle'), t('Storage.UpdateErrorBody'), e));
function showUpdateErrorNotification(e: unknown) {
showNotification(
dimErrorToaster(t('Storage.UpdateErrorTitle'), t('Storage.UpdateErrorBody'), errorMessage(e))
);
}
9 changes: 5 additions & 4 deletions src/app/dim-api/import.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { Settings, initialSettingsState } from 'app/settings/initial-settings';
import { ThunkResult } from 'app/store/types';
import { errorLog, infoLog } from 'app/utils/log';
import { observeStore } from 'app/utils/redux-utils';
import { errorMessage } from 'app/utils/util';
import _ from 'lodash';
import { loadDimApiData } from './actions';
import { profileLoadedFromIDB } from './basic-actions';
Expand Down Expand Up @@ -45,7 +46,7 @@ export function importDataBackup(data: ExportResponse, silent = false): ThunkRes
} catch (e) {
if (!silent) {
errorLog('importLegacyData', 'Error importing legacy data into DIM API', e);
showImportFailedNotification(e);
showImportFailedNotification(errorMessage(e));
}
return;
}
Expand All @@ -65,7 +66,7 @@ export function importDataBackup(data: ExportResponse, silent = false): ThunkRes
'Error importing legacy data into DIM - no data found in import file. (no settings upgrade/API upload attempted. DIM Sync is turned off)',
data
);
showImportFailedNotification(new Error(t('Storage.ImportNotification.NoData')));
showImportFailedNotification(t('Storage.ImportNotification.NoData'));
}
return;
}
Expand Down Expand Up @@ -176,11 +177,11 @@ function showImportSuccessNotification(
});
}

function showImportFailedNotification(e: Error) {
function showImportFailedNotification(message: string) {
showNotification({
type: 'error',
title: t('Storage.ImportNotification.FailedTitle'),
body: t('Storage.ImportNotification.FailedBody', { error: e.message }),
body: t('Storage.ImportNotification.FailedBody', { error: message }),
duration: 15000,
});
}
Expand Down
3 changes: 2 additions & 1 deletion src/app/inventory/bulk-actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import NotificationButton from 'app/notifications/NotificationButton';
import { showNotification } from 'app/notifications/notifications';
import { AppIcon, undoIcon } from 'app/shell/icons';
import { ThunkResult } from 'app/store/types';
import { errorMessage } from 'app/utils/util';
import _ from 'lodash';
import { canSyncLockState } from './SyncTagLock';
import { setItemHashTag, setItemTagsBulk } from './actions';
Expand Down Expand Up @@ -128,7 +129,7 @@ export function bulkLockItems(items: DimItem[], locked: boolean): ThunkResult {
showNotification({
type: 'error',
title: locked ? t('Filter.LockAllFailed') : t('Filter.UnlockAllFailed'),
body: e.message,
body: errorMessage(e),
});
}
};
Expand Down
Loading

0 comments on commit 7a1ce26

Please sign in to comment.