Skip to content

Commit

Permalink
Cast unknowns to errors in catch blocks (#6362)
Browse files Browse the repository at this point in the history
  • Loading branch information
dwyfrequency committed Jun 15, 2022
1 parent b091b02 commit 8e952e2
Show file tree
Hide file tree
Showing 18 changed files with 48 additions and 38 deletions.
11 changes: 6 additions & 5 deletions packages/firestore/src/api/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,15 +328,16 @@ function setPersistenceProviders(
await setOnlineComponentProvider(client, onlineComponentProvider);
persistenceResult.resolve();
} catch (e) {
if (!canFallbackFromIndexedDbError(e)) {
throw e;
const error = e as FirestoreError | DOMException;
if (!canFallbackFromIndexedDbError(error)) {
throw error;
}
console.warn(
'Error enabling offline persistence. Falling back to ' +
'persistence disabled: ' +
e
error
);
persistenceResult.reject(e);
persistenceResult.reject(error);
}
})
.then(() => persistenceResult.promise);
Expand Down Expand Up @@ -419,7 +420,7 @@ export function clearIndexedDbPersistence(firestore: Firestore): Promise<void> {
);
deferred.resolve();
} catch (e) {
deferred.reject(e);
deferred.reject(e as Error | undefined);
}
});
return deferred.promise;
Expand Down
2 changes: 1 addition & 1 deletion packages/firestore/src/api/index_configuration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ function tryParseJson(json: string): Record<string, unknown> {
} catch (e) {
throw new FirestoreError(
Code.INVALID_ARGUMENT,
'Failed to parse JSON:' + e.message
'Failed to parse JSON:' + (e as Error)?.message
);
}
}
Expand Down
6 changes: 3 additions & 3 deletions packages/firestore/src/core/firestore_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ export class FirestoreClient {
deferred.resolve();
} catch (e) {
const firestoreError = wrapInUserErrorIfRecoverable(
e,
e as Error,
`Failed to shutdown persistence`
);
deferred.reject(firestoreError);
Expand Down Expand Up @@ -525,7 +525,7 @@ async function readDocumentFromCache(
}
} catch (e) {
const firestoreError = wrapInUserErrorIfRecoverable(
e,
e as Error,
`Failed to get document '${docKey} from cache`
);
result.reject(firestoreError);
Expand Down Expand Up @@ -623,7 +623,7 @@ async function executeQueryFromCache(
result.resolve(viewChange.snapshot!);
} catch (e) {
const firestoreError = wrapInUserErrorIfRecoverable(
e,
e as Error,
`Failed to execute query '${query} against cache`
);
result.reject(firestoreError);
Expand Down
15 changes: 9 additions & 6 deletions packages/firestore/src/core/sync_engine_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,10 @@ export async function syncEngineWrite(
} catch (e) {
// If we can't persist the mutation, we reject the user callback and
// don't send the mutation. The user can then retry the write.
const error = wrapInUserErrorIfRecoverable(e, `Failed to persist write`);
const error = wrapInUserErrorIfRecoverable(
e as Error,
`Failed to persist write`
);
userCallback.reject(error);
}
}
Expand Down Expand Up @@ -532,7 +535,7 @@ export async function syncEngineApplyRemoteEvent(
remoteEvent
);
} catch (error) {
await ignoreIfPrimaryLeaseLoss(error);
await ignoreIfPrimaryLeaseLoss(error as FirestoreError);
}
}

Expand Down Expand Up @@ -684,7 +687,7 @@ export async function syncEngineApplySuccessfulWrite(
);
await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes);
} catch (error) {
await ignoreIfPrimaryLeaseLoss(error);
await ignoreIfPrimaryLeaseLoss(error as FirestoreError);
}
}

Expand Down Expand Up @@ -715,7 +718,7 @@ export async function syncEngineRejectFailedWrite(
);
await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes);
} catch (error) {
await ignoreIfPrimaryLeaseLoss(error);
await ignoreIfPrimaryLeaseLoss(error as FirestoreError);
}
}

Expand Down Expand Up @@ -752,7 +755,7 @@ export async function syncEngineRegisterPendingWritesCallback(
syncEngineImpl.pendingWritesCallbacks.set(highestBatchId, callbacks);
} catch (e) {
const firestoreError = wrapInUserErrorIfRecoverable(
e,
e as Error,
'Initialization of waitForPendingWrites() operation failed'
);
callback.reject(firestoreError);
Expand Down Expand Up @@ -1628,7 +1631,7 @@ async function loadBundleImpl(
return Promise.resolve(result.changedCollectionGroups);
} catch (e) {
logWarn(LOG_TAG, `Loading bundle failed with ${e}`);
task._failWith(e);
task._failWith(e as FirestoreError);
return Promise.resolve(new Set<string>());
}
}
2 changes: 1 addition & 1 deletion packages/firestore/src/core/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ export class Transaction {
try {
this.write(data.toMutation(key, this.preconditionForUpdate(key)));
} catch (e) {
this.lastWriteError = e;
this.lastWriteError = e as FirestoreError | null;
}
this.writtenDocs.add(key.toString());
}
Expand Down
2 changes: 1 addition & 1 deletion packages/firestore/src/core/transaction_runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export class TransactionRunner<T> {
return userPromise;
} catch (error) {
// Do not retry errors thrown by user provided updateFunction.
this.deferred.reject(error);
this.deferred.reject(error as Error);
return null;
}
}
Expand Down
5 changes: 3 additions & 2 deletions packages/firestore/src/local/index_backfiller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { FirestoreError } from '../api';
import { DocumentMap } from '../model/collections';
import {
IndexOffset,
Expand Down Expand Up @@ -90,14 +91,14 @@ export class IndexBackfillerScheduler implements Scheduler {
const documentsProcessed = await this.backfiller.backfill();
logDebug(LOG_TAG, `Documents written: ${documentsProcessed}`);
} catch (e) {
if (isIndexedDbTransactionError(e)) {
if (isIndexedDbTransactionError(e as Error)) {
logDebug(
LOG_TAG,
'Ignoring IndexedDB error during index backfill: ',
e
);
} else {
await ignoreIfPrimaryLeaseLoss(e);
await ignoreIfPrimaryLeaseLoss(e as FirestoreError);
}
}
await this.schedule(REGULAR_BACKFILL_DELAY_MS);
Expand Down
4 changes: 2 additions & 2 deletions packages/firestore/src/local/local_store_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -844,7 +844,7 @@ export async function localStoreNotifyLocalViewChanges(
}
);
} catch (e) {
if (isIndexedDbTransactionError(e)) {
if (isIndexedDbTransactionError(e as Error)) {
// If `notifyLocalViewChanges` fails, we did not advance the sequence
// number for the documents that were included in this transaction.
// This might trigger them to be deleted earlier than they otherwise
Expand Down Expand Up @@ -1039,7 +1039,7 @@ export async function localStoreReleaseTarget(
);
}
} catch (e) {
if (isIndexedDbTransactionError(e)) {
if (isIndexedDbTransactionError(e as Error)) {
// All `releaseTarget` does is record the final metadata state for the
// target, but we've been recording this periodically during target
// activity. If we lose this write this could cause a very slight
Expand Down
5 changes: 3 additions & 2 deletions packages/firestore/src/local/lru_garbage_collector_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
* limitations under the License.
*/

import { FirestoreError } from '../api';
import { ListenSequence } from '../core/listen_sequence';
import { ListenSequenceNumber } from '../core/types';
import { debugAssert } from '../util/assert';
Expand Down Expand Up @@ -159,14 +160,14 @@ export class LruScheduler implements Scheduler {
try {
await this.localStore.collectGarbage(this.garbageCollector);
} catch (e) {
if (isIndexedDbTransactionError(e)) {
if (isIndexedDbTransactionError(e as Error)) {
logDebug(
LOG_TAG,
'Ignoring IndexedDB error during garbage collection: ',
e
);
} else {
await ignoreIfPrimaryLeaseLoss(e);
await ignoreIfPrimaryLeaseLoss(e as FirestoreError);
}
}
await this.scheduleGC(REGULAR_GC_DELAY_MS);
Expand Down
2 changes: 1 addition & 1 deletion packages/firestore/src/local/persistence_promise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ export class PersistencePromise<T> {
return PersistencePromise.resolve(result);
}
} catch (e) {
return PersistencePromise.reject<R>(e);
return PersistencePromise.reject<R>(e as Error);
}
}

Expand Down
5 changes: 3 additions & 2 deletions packages/firestore/src/local/simple_db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export class SimpleDbTransaction {
db.transaction(objectStoreNames, mode)
);
} catch (e) {
throw new IndexedDbTransactionError(action, e);
throw new IndexedDbTransactionError(action, e as Error);
}
}

Expand Down Expand Up @@ -434,7 +434,8 @@ export class SimpleDb {
// caller.
await transaction.completionPromise;
return transactionFnResult;
} catch (error) {
} catch (e) {
const error = e as Error;
// TODO(schmidt-sebastian): We could probably be smarter about this and
// not retry exceptions that are likely unrecoverable (such as quota
// exceeded errors).
Expand Down
6 changes: 3 additions & 3 deletions packages/firestore/src/remote/remote_store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ async function onWatchStreamChange(
watchChange.targetIds.join(','),
e
);
await disableNetworkUntilRecovery(remoteStoreImpl, e);
await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);
}
return;
}
Expand Down Expand Up @@ -481,7 +481,7 @@ async function onWatchStreamChange(
}
} catch (e) {
logDebug(LOG_TAG, 'Failed to raise snapshot:', e);
await disableNetworkUntilRecovery(remoteStoreImpl, e);
await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);
}
}
}
Expand Down Expand Up @@ -675,7 +675,7 @@ export async function fillWritePipeline(
addToWritePipeline(remoteStoreImpl, batch);
}
} catch (e) {
await disableNetworkUntilRecovery(remoteStoreImpl, e);
await disableNetworkUntilRecovery(remoteStoreImpl, e as FirestoreError);
}
}

Expand Down
2 changes: 1 addition & 1 deletion packages/firestore/src/util/async_queue_impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ export class AsyncQueueImpl implements AsyncQueue {
this.retryableOps.shift();
this.backoff.reset();
} catch (e) {
if (isIndexedDbTransactionError(e)) {
if (isIndexedDbTransactionError(e as Error)) {
logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e);
} else {
throw e; // Failure will be handled by AsyncQueue
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ import {
setDoc,
updateDoc,
arrayRemove,
arrayUnion
arrayUnion,
FirestoreError
} from '../util/firebase_export';
import { apiDescribe, withTestDb, withTestDoc } from '../util/helpers';

Expand Down Expand Up @@ -191,7 +192,7 @@ apiDescribe('Array Transforms:', (persistence: boolean) => {
try {
await getDocFromCache(docRef);
} catch (err) {
expect(err.code).to.equal('unavailable');
expect((err as FirestoreError).code).to.equal('unavailable');
errCaught = true;
}
expect(errCaught).to.be.true;
Expand Down
4 changes: 3 additions & 1 deletion packages/firestore/test/lite/integration.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,9 @@ describe('Firestore', () => {
getDoc(doc(firestore, 'coll/doc'));
expect.fail();
} catch (e) {
expect(e.message).to.equal('The client has already been terminated.');
expect((e as Error)?.message).to.equal(
'The client has already been terminated.'
);
}
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1246,9 +1246,9 @@ describe('IndexedDbSchema: createOrUpgradeDb', () => {
);
await db.ensureDb(this.test!.fullTitle());
} catch (e) {
error = e;
error = e as FirestoreError;
expect(
e.message.indexOf('A newer version of the Firestore SDK')
error?.message?.indexOf('A newer version of the Firestore SDK')
).to.not.equal(-1);
}
expect(error).to.not.be.null;
Expand Down
2 changes: 1 addition & 1 deletion packages/firestore/test/unit/util/async_queue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ function defer<T>(op: () => T): Promise<T> {
try {
resolve(op());
} catch (e) {
reject(e);
reject(e as Error);
}
}, 0);
});
Expand Down
4 changes: 2 additions & 2 deletions packages/messaging/src/internals/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export async function requestGetToken(
responseData = await response.json();
} catch (err) {
throw ERROR_FACTORY.create(ErrorCode.TOKEN_SUBSCRIBE_FAILED, {
errorInfo: err
errorInfo: (err as Error)?.toString()
});
}

Expand Down Expand Up @@ -98,7 +98,7 @@ export async function requestUpdateToken(
responseData = await response.json();
} catch (err) {
throw ERROR_FACTORY.create(ErrorCode.TOKEN_UPDATE_FAILED, {
errorInfo: err
errorInfo: (err as Error)?.toString()
});
}

Expand Down

0 comments on commit 8e952e2

Please sign in to comment.