Skip to content

Commit

Permalink
refactor: clean up throwing errors (#219)
Browse files Browse the repository at this point in the history
  • Loading branch information
blaugold committed Nov 5, 2021
1 parent 46da1b0 commit 76871d1
Show file tree
Hide file tree
Showing 19 changed files with 133 additions and 140 deletions.
24 changes: 11 additions & 13 deletions packages/cbl/lib/src/document/blob.dart
Expand Up @@ -6,8 +6,10 @@ import 'package:meta/meta.dart';

import '../database/blob_store.dart';
import '../database/database.dart';
import '../errors.dart';
import '../fleece/encoder.dart';
import '../fleece/fleece.dart';
import '../support/errors.dart';
import '../support/streams.dart';
import '../support/utils.dart';
import 'common.dart';
Expand Down Expand Up @@ -113,9 +115,11 @@ class BlobImpl implements Blob, FleeceEncodable, CblConversions {
// ignore: unnecessary_parenthesis
_content = (properties[blobDataProperty] as Uint8List?) {
if (_digest == null && _content == null) {
throw StateError(
throw ArgumentError.value(
properties,
'properties',
'Blob loaded from database has neither the `digest` nor the `data` '
'property.',
'property.',
);
}
}
Expand Down Expand Up @@ -238,7 +242,7 @@ class BlobImpl implements Blob, FleeceEncodable, CblConversions {
if (context != null && context.saveExternalData) {
final database = context.database;
if (database != null) {
_checkBlobIsFromSameDatabase(database);
assertMatchingDatabase(_database, database, 'Blob');
_database = database;

if (_digest == null) {
Expand Down Expand Up @@ -309,15 +313,9 @@ class BlobImpl implements Blob, FleeceEncodable, CblConversions {
}

Never _throwNotFoundError() {
throw StateError('Could not find blob in $_database: $_blobProperties');
}

void _checkBlobIsFromSameDatabase(Object database) {
if (_database != null && _database != database) {
throw StateError(
'A document contains a blob that was saved to a different database. '
'The save operation cannot complete.',
);
}
throw DatabaseException(
'Could not find blob in $_database: $_blobProperties',
DatabaseErrorCode.notFound,
);
}
}
21 changes: 6 additions & 15 deletions packages/cbl/lib/src/document/document.dart
Expand Up @@ -7,6 +7,7 @@ import '../database/database.dart';
import '../fleece/fleece.dart' as fl;
import '../fleece/integration/integration.dart';
import '../support/encoding.dart';
import '../support/errors.dart';
import '../support/utils.dart';
import 'array.dart';
import 'blob.dart';
Expand Down Expand Up @@ -122,7 +123,7 @@ class DocumentMContext extends MContext implements DatabaseMContext {
final DelegateDocument document;

@override
Database get database => document.database!;
Database get database => document.database;
}

class DelegateDocument with IterableMixin<String> implements Document {
Expand Down Expand Up @@ -152,21 +153,13 @@ class DelegateDocument with IterableMixin<String> implements Document {
}
}

Database? get database => _database;
Database get database => _database!;
Database? _database;

set database(Database? database) {
if (_database == database) {
return;
set database(Database database) {
if (assertMatchingDatabase(_database, database, 'Document')) {
_database = database;
}

if (_database != null) {
throw StateError(
'The document cannot be used with $database because it already '
'belongs to $_database: $this',
);
}
_database = database;
}

void setProperties(EncodedData properties) {
Expand All @@ -178,8 +171,6 @@ class DelegateDocument with IterableMixin<String> implements Document {
EncodingFormat format = EncodingFormat.fleece,
bool saveExternalData = false,
}) {
assert(database != null);

final encoder = fl.FleeceEncoder(format: format.toFLEncoderFormat())
..extraInfo = FleeceEncoderContext(
database: database,
Expand Down
9 changes: 2 additions & 7 deletions packages/cbl/lib/src/document/fragment.dart
@@ -1,6 +1,7 @@
// ignore: lines_longer_than_80_chars
// ignore_for_file: cast_nullable_to_non_nullable, avoid_setters_without_getters, one_member_abstracts

import '../support/errors.dart';
import 'array.dart';
import 'blob.dart';
import 'dictionary.dart';
Expand Down Expand Up @@ -279,13 +280,7 @@ class FragmentImpl implements Fragment {
_updateSubscript(indexOrKey) ? this : _emptyInstance;

bool _updateSubscript(Object indexOrKey) {
if (indexOrKey is! int && indexOrKey is! String) {
throw ArgumentError.value(
indexOrKey,
'indexOrKey',
'must be of type int or String',
);
}
assertIndexOrKey(indexOrKey);

final value = this.value;

Expand Down
22 changes: 7 additions & 15 deletions packages/cbl/lib/src/fleece/containers.dart
Expand Up @@ -505,16 +505,10 @@ class Dict extends Value with MapMixin<String, Value> {
late final Iterable<String> keys = _DictKeyIterable(this);

@override
Value operator [](Object? key) {
if (key is! String) {
throw ArgumentError.value(key, 'key', 'must be a String');
}

return Value.fromPointer(
native.call((pointer) => _bindings.get(pointer.cast(), key)),
isRefCounted: false,
);
}
Value operator [](Object? key) => Value.fromPointer(
native.call((pointer) => _bindings.get(pointer.cast(), assertKey(key))),
isRefCounted: false,
);

@override
void operator []=(String key, Object? value) =>
Expand Down Expand Up @@ -669,13 +663,11 @@ class MutableDict extends Dict {

@override
Value? remove(Object? key) {
if (key is! String) {
throw ArgumentError.value(key, 'kye', 'must be a String');
}
final _key = assertKey(key);

final value = this[key];
final value = this[_key];

native.call((pointer) => _bindings.remove(pointer.cast(), key));
native.call((pointer) => _bindings.remove(pointer.cast(), _key));

return value;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/cbl/lib/src/fleece/encoder.dart
Expand Up @@ -183,7 +183,7 @@ class FleeceEncoder extends FleeceEncoderObject {
final result = call(_encoderBinds.finish);

if (result == null) {
throw StateError('Encoder did not encode anything');
throw StateError('Encoder did not encode anything.');
}

return result;
Expand Down
8 changes: 2 additions & 6 deletions packages/cbl/lib/src/log/file_logger.dart
Expand Up @@ -47,7 +47,7 @@ class LogFileConfiguration {

set maxSize(int maxSize) {
if (maxSize <= 0) {
throw ArgumentError.value(maxSize, 'maxSize', 'must be greater than 0');
throw RangeError.range(maxSize, 1, null, 'maxSize');
}
_maxSize = maxSize;
}
Expand All @@ -60,11 +60,7 @@ class LogFileConfiguration {

set maxRotateCount(int maxRotateCount) {
if (maxRotateCount < 0) {
throw ArgumentError.value(
maxRotateCount,
'maxRotateCount',
'must be greater or the same as 0',
);
throw RangeError.range(maxRotateCount, 0, null, 'maxRotateCount');
}
_maxRotateCount = maxRotateCount;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/cbl/lib/src/query/parameters.dart
Expand Up @@ -154,7 +154,7 @@ class ParametersImpl implements Parameters, FleeceEncodable {

void _checkReadonly() {
if (_readonly) {
throw StateError('This parameters object is readonly.');
throw StateError('These parameters are readonly.');
}
}

Expand Down
4 changes: 1 addition & 3 deletions packages/cbl/lib/src/query/query_builder.dart
Expand Up @@ -308,9 +308,7 @@ mixin BuilderQueryMixin on QueryBase {

void _checkHasFrom() {
if (_from == null) {
throw StateError(
'Ensure that a query has a FROM clause before using it.',
);
throw StateError('Query has no FROM clause.');
}
}
}
30 changes: 16 additions & 14 deletions packages/cbl/lib/src/query/select.dart
Expand Up @@ -102,13 +102,7 @@ class SyncSelectImpl extends SyncBuilderQuery implements SyncSelect {

@override
SyncFrom from(DataSourceInterface dataSource) {
if ((dataSource as DataSourceImpl).database is! SyncDatabase) {
throw ArgumentError(
'`SyncQueryBuilder` must be used with a `SyncDatabase`. '
'To build a query for an `AsyncDatabase` use `AsyncQueryBuilder`.',
);
}

_assertDataSourceDatabaseType<SyncDatabase>(dataSource, 'Sync', 'Async');
return SyncFromImpl(query: this, from: dataSource);
}
}
Expand All @@ -121,13 +115,21 @@ class AsyncSelectImpl extends AsyncBuilderQuery implements AsyncSelect {

@override
AsyncFrom from(DataSourceInterface dataSource) {
if ((dataSource as DataSourceImpl).database is! AsyncDatabase) {
throw ArgumentError(
'`AsyncQueryBuilder` must be used with an `AsyncDatabase`. '
'To build a query for a `SyncDatabase` use `SyncQueryBuilder`.',
);
}

_assertDataSourceDatabaseType<AsyncDatabase>(dataSource, 'Async', 'Sync');
return AsyncFromImpl(query: this, from: dataSource);
}
}

void _assertDataSourceDatabaseType<T>(
DataSourceInterface dataSource,
String expectedStyle,
String actualStyle,
) {
if ((dataSource as DataSourceImpl).database is! T) {
throw ArgumentError(
'${expectedStyle}QueryBuilder must be used with an '
'${expectedStyle}Database. To build a query for a ${actualStyle}Database '
'use ${actualStyle}QueryBuilder.',
);
}
}
30 changes: 14 additions & 16 deletions packages/cbl/lib/src/replication/configuration.dart
Expand Up @@ -183,18 +183,19 @@ class ReplicatorConfiguration {
/// the other peer is still alive.
///
/// Setting this value to [Duration.zero] or a negative [Duration] will
/// result in an [ArgumentError] being thrown.
/// result in an [RangeError] being thrown.
///
/// To use the default of 300 seconds, set this property to `null`.
Duration? get heartbeat => _heartbeat;
Duration? _heartbeat;

set heartbeat(Duration? heartbeat) {
if (heartbeat != null && heartbeat.inSeconds <= 0) {
throw ArgumentError.value(
heartbeat,
'heartbeat',
'must not be zero or negative',
throw RangeError.range(
heartbeat.inSeconds,
1,
null,
'heartbeat.inSeconds',
);
}
_heartbeat = heartbeat;
Expand All @@ -210,18 +211,14 @@ class ReplicatorConfiguration {
/// replicators will be applied.
/// Setting the value to `1` with result in no retry attempts.
///
/// Setting `0` a negative number will result in an [ArgumentError] being
/// Setting `0` a negative number will result in an [RangeError] being
/// thrown.
int? get maxAttempts => _maxAttempts;
int? _maxAttempts;

set maxAttempts(int? maxAttempts) {
if (maxAttempts != null && maxAttempts <= 0) {
throw ArgumentError.value(
maxAttempts,
'maxAttempts',
'must not be zero or negative',
);
throw RangeError.range(maxAttempts, 1, null, 'maxAttempts');
}
_maxAttempts = maxAttempts;
}
Expand All @@ -232,18 +229,19 @@ class ReplicatorConfiguration {
/// customized.
///
/// Setting this value to [Duration.zero] or a negative [Duration] will
/// result in an [ArgumentError] being thrown.
/// result in an [RangeError] being thrown.
///
/// To use the default of 300 seconds, set this property to `null`.
Duration? get maxAttemptWaitTime => _maxAttemptWaitTime;
Duration? _maxAttemptWaitTime;

set maxAttemptWaitTime(Duration? maxAttemptWaitTime) {
if (maxAttemptWaitTime != null && maxAttemptWaitTime.inSeconds <= 0) {
throw ArgumentError.value(
maxAttemptWaitTime,
'maxAttemptWaitTime',
'must not be zero or negative',
throw RangeError.range(
maxAttemptWaitTime.inSeconds,
1,
null,
'maxAttemptWaitTime.inSeconds',
);
}
_maxAttemptWaitTime = maxAttemptWaitTime;
Expand Down
24 changes: 8 additions & 16 deletions packages/cbl/lib/src/replication/ffi_replicator.dart
Expand Up @@ -5,6 +5,7 @@ import 'dart:io';
import 'package:cbl_ffi/cbl_ffi.dart';
import 'package:collection/collection.dart';

import '../database.dart';
import '../database/ffi_database.dart';
import '../document/document.dart';
import '../document/ffi_document.dart';
Expand Down Expand Up @@ -37,26 +38,17 @@ class FfiReplicator
required String debugCreator,
bool ignoreCallbackErrorsInDart = false,
}) : _config = ReplicatorConfiguration.from(config) {
final database = _config.database;
if (database is! FfiDatabase) {
throw ArgumentError.value(
config.database,
'config.database',
'must by a SyncDatabase',
);
}
final database =
assertArgumentType<SyncDatabase>(config.database, 'config.database')
as FfiDatabase;

final target = config.target;
if (target is DatabaseEndpoint) {
useEnterpriseFeature(EnterpriseFeature.localDbReplication);

if (target.database is! FfiDatabase) {
throw ArgumentError.value(
target,
'config.target.database',
'must by a SyncDatabase',
);
}
assertArgumentType<SyncDatabase>(
target.database,
'config.target.database',
);
}

_database = database;
Expand Down

0 comments on commit 76871d1

Please sign in to comment.