Better error handling for powersync errors

This new logic properly handles retriable and transient errors
This commit is contained in:
Roland Geider
2026-06-04 20:41:06 +02:00
parent 0d3d7d7cba
commit ca2530ecab
6 changed files with 221 additions and 56 deletions

View File

@@ -87,6 +87,14 @@ void showHttpExceptionErrorDialog(WgerHttpException exception, {BuildContext? co
).whenComplete(() => _errorDialogVisible = false);
}
/// Flattens a [WgerHttpException]'s context and error map into a readable
/// multi-line string for the diagnostic dialog and bug report.
String _formatHttpExceptionDetail(WgerHttpException error) {
String lines(Map<String, dynamic> m) => m.entries.map((e) => '${e.key}: ${e.value}').join('\n');
final ctx = error.context == null || error.context!.isEmpty ? '' : '${lines(error.context!)}\n\n';
return '$ctx${lines(error.errors)}';
}
void showGeneralErrorDialog(dynamic error, StackTrace? stackTrace, {BuildContext? context}) {
// Attempt to get the BuildContext from our global navigatorKey.
// This allows us to show a dialog even if the error occurs outside
@@ -120,6 +128,14 @@ void showGeneralErrorDialog(dynamic error, StackTrace? stackTrace, {BuildContext
issueErrorMessage = error.exceptionAsString();
} else if (error is MissingRequiredKeysException) {
issueTitle = 'Missing Required Key';
} else if (error is WgerHttpException) {
final status = error.statusCode == null ? '' : ' (HTTP ${error.statusCode})';
issueTitle = switch (error.source) {
ExceptionSource.powersync => 'Sync upload rejected$status',
ExceptionSource.flutter => 'Application error$status',
ExceptionSource.api => 'Server error$status',
};
issueErrorMessage = _formatHttpExceptionDetail(error);
}
final String fullStackTrace = stackTrace?.toString() ?? 'No stack trace available.';
@@ -246,7 +262,9 @@ void handleError(Object? error, StackTrace? stackTrace) {
case ErrorSeverity.transient:
showTransientErrorSnackbar();
case ErrorSeverity.fatal:
if (error is WgerHttpException) {
// API errors are the form-validation fallback (clean field errors);
// other sources are diagnostic and get the dialog with logs and report.
if (error is WgerHttpException && error.source == ExceptionSource.api) {
showHttpExceptionErrorDialog(error);
} else {
showGeneralErrorDialog(error, stackTrace);

View File

@@ -27,6 +27,11 @@ enum ErrorType {
text,
}
/// Where an exception originated, so the error handler can route and present
/// it differently (a plain API validation error vs a PowerSync upload
/// rejection worth reporting).
enum ExceptionSource { api, powersync, flutter }
const HTML_ERROR_KEY = 'html_error';
class WgerHttpException implements Exception {
@@ -37,8 +42,21 @@ class WgerHttpException implements Exception {
/// or similar.
late ErrorType type;
/// Where the exception came from (drives routing and presentation).
final ExceptionSource source;
/// The HTTP status code, when built from a [Response].
final int? statusCode;
/// Optional structured context for diagnostics (e.g. the PowerSync table/op).
final Map<String, dynamic>? context;
/// Custom http exception
WgerHttpException(Response response) {
WgerHttpException(
Response response, {
this.source = ExceptionSource.api,
this.context,
}) : statusCode = response.statusCode {
type = ErrorType.json;
final dynamic responseBody = response.body;
@@ -67,7 +85,12 @@ class WgerHttpException implements Exception {
}
}
WgerHttpException.fromMap(Map<String, dynamic> map) : type = ErrorType.json {
WgerHttpException.fromMap(
Map<String, dynamic> map, {
this.source = ExceptionSource.api,
this.statusCode,
this.context,
}) : type = ErrorType.json {
errors = map;
}
@@ -81,6 +104,7 @@ class WgerHttpException implements Exception {
@override
String toString() {
return 'WgerHttpException ($type): $errors';
final ctxStr = context == null ? '' : ', context: $context';
return 'WgerHttpException(${source.name}, status ${statusCode ?? '-'}, $type): $errors$ctxStr';
}
}

View File

@@ -56,12 +56,11 @@ class ApiClient {
throw Exception('Failed to fetch token');
}
// The methods below return the raw [http.Response] so the connector
// can inspect the status code and the JSON body. The backend always
// answers 200 (PowerSync-recommended pattern: non-2xx triggers an
// infinite retry loop on the SDK side, which is wrong for permanent
// rejections like validation failures), but encodes any rejection
// as `{'error': '...', 'details': ...}` in the body.
// Return the raw [http.Response] so the connector can inspect status and
// body. The backend encodes permanent rejections as 200 + `{'error': ...}`
// (a non-2xx would trigger PowerSync's retry loop). Infrastructure and
// unhandled 5xx aren't part of that contract; the connector classifies and
// retries those.
Future<http.Response> upsert(Map<String, dynamic> record) {
return _client.put(uri, headers: getHeaders(), body: json.encode(record));
}

View File

@@ -25,33 +25,42 @@ import 'package:http/http.dart' as http;
import 'package:logging/logging.dart';
import 'package:powersync/powersync.dart';
import 'package:wger/core/error_dialogs.dart';
import 'package:wger/core/exceptions/http_exception.dart';
import 'package:wger/helpers/jwt.dart';
import 'package:wger/powersync/api_client.dart';
final logger = Logger('powersync-django');
/// Exception thrown when the wger backend returned a 200 response whose
/// body indicates that the operation was rejected (validation failure,
/// missing object, ownership violation, unknown table…). Carries the
/// raw error map so the global error dialog can display the detail.
class BackendUploadException implements Exception {
/// Thrown for an upload status that should be retried, not discarded such as
/// HTTP status codes 5xx, 408, 429, or an unrecovered 401. Throwing leaves the
/// transaction queued for PowerSync to retry. Carries table/op/status for
/// logging and tests.
class RetryableUploadException implements Exception {
final String table;
final UpdateType op;
final String error;
final Object? details;
final int statusCode;
BackendUploadException({
RetryableUploadException({
required this.table,
required this.op,
required this.error,
required this.details,
required this.statusCode,
});
@override
String toString() {
final detailsStr = details == null ? '' : '\n$details';
return 'Backend rejected $op on $table: $error$detailsStr';
}
String toString() => 'Upload of $op on $table deferred: retryable status $statusCode';
}
/// What the transaction loop does with one upload response.
enum _UploadOutcome {
/// Accepted: complete the transaction once all ops are ok.
ok,
/// Permanently refused: surface it but still complete, so one bad op can't
/// block the queue.
reject,
/// Retryable: throw so PowerSync retries the queued transaction later.
retry,
}
class DjangoConnector extends PowerSyncBackendConnector {
@@ -170,10 +179,13 @@ class DjangoConnector extends PowerSyncBackendConnector {
await processTransaction(transaction);
}
/// Uploads every op in [transaction] and, on success, completes it so the
/// ops leave the local queue. Backend rejections are reported but swallowed
/// (see [_handleUploadResponse]), and a network error rethrows so PowerSync
/// retries the whole transaction once the backend is reachable again.
/// Uploads every op in [transaction] and decides its fate: all accepted
/// completes it; a permanent refusal is surfaced but still completes (so one
/// bad op can't block the queue); a transient status (5xx, 408, 429, 401) or
/// an unreachable backend throws, leaving it queued for PowerSync to retry.
///
/// A retry re-sends the whole transaction (at-least-once), so backend handlers
/// must be idempotent.
@visibleForTesting
Future<void> processTransaction(CrudTransaction transaction) async {
try {
@@ -198,7 +210,19 @@ class DjangoConnector extends PowerSyncBackendConnector {
break;
}
_handleUploadResponse(op, response);
switch (_classifyResponse(response)) {
case _UploadOutcome.ok:
break;
case _UploadOutcome.reject:
_reportRejection(op, response);
break;
case _UploadOutcome.retry:
throw RetryableUploadException(
table: op.table,
op: op.op,
statusCode: response.statusCode,
);
}
}
await transaction.complete();
} on http.ClientException catch (e) {
@@ -209,45 +233,79 @@ class DjangoConnector extends PowerSyncBackendConnector {
} on SocketException catch (e) {
logger.fine('Upload deferred, backend unreachable: ${e.message}');
rethrow;
} on RetryableUploadException catch (e) {
// Stays queued for PowerSync to retry. Below severe: a brief server blip
// is expected to clear on its own.
logger.warning('Upload deferred: $e');
rethrow;
} on Exception catch (e) {
logger.severe('Error uploading data', e);
// Error may be retryable - e.g. network error or temporary server error.
// Throwing an error here causes this call to be retried after a delay.
// Error may be retryable, e.g. a temporary server error. Throwing here
// causes PowerSync to retry this transaction after a delay.
rethrow;
}
}
/// Inspects the backend response for a given CRUD op. If the body reports a
/// logical / validation rejection we surface it via the global error dialog
/// but do **not** rethrow, otherwise that would trigger a PowerSync retry loop.
void _handleUploadResponse(CrudEntry op, http.Response response) {
if (response.statusCode != 200 || response.body.isEmpty) {
return;
/// Classifies a single upload [response] into a [_UploadOutcome].
_UploadOutcome _classifyResponse(http.Response response) {
final status = response.statusCode;
// 2xx is success, unless the backend encoded a permanent rejection as
// 200 + `{error}` (its anti-retry-storm contract).
if (status >= 200 && status < 300) {
return _isErrorBody(response) ? _UploadOutcome.reject : _UploadOutcome.ok;
}
final Object? decoded;
try {
decoded = json.decode(response.body);
} on FormatException {
// Non-JSON response on a 200, uncommon but harmless to ignore.
return;
}
if (decoded is! Map<String, dynamic> || !decoded.containsKey('error')) {
return;
// Transient or retryable. 401 lands here because AuthHttpClient already
// tried to refresh; a 401 still reaching us means the session is gone, so
// queue the op for re-auth rather than dropping it.
if (status >= 500 || status == 408 || status == 429 || status == 401) {
return _UploadOutcome.retry;
}
// Any other 4xx is permanent (retry won't help). Expected refusals come as
// 200 + `{error}`, so a non-200 4xx is genuinely unexpected.
return _UploadOutcome.reject;
}
/// Surfaces a permanently refused op via the global error dialog, once per op
/// per session (a re-driven transaction would otherwise re-pop it each tick).
void _reportRejection(CrudEntry op, http.Response response) {
if (!_reportedFailedOps.add(op.id)) {
// Already shown for this operation in the current session.
return;
}
final exception = BackendUploadException(
table: op.table,
op: op.op,
error: decoded['error']?.toString() ?? 'Unknown error',
details: decoded['details'],
final exception = WgerHttpException(
response,
source: ExceptionSource.powersync,
context: {'table': op.table, 'op': op.op.name},
);
logger.warning('Backend rejected upload', exception);
showGeneralErrorDialog(exception, StackTrace.current);
final ctx = '${op.op.name} ${op.table}';
// 200 + {error} is the expected contract (warning); other statuses are
// unexpected (severe).
if (response.statusCode == 200) {
logger.warning('Backend rejected $ctx', exception);
} else {
logger.severe('Unexpected permanent upload failure: $ctx', exception);
}
// Route through the app's central error handler (same entry point as the
// global FlutterError/PlatformDispatcher handlers).
handleError(exception, StackTrace.current);
}
/// Whether [response]'s body is a JSON object carrying an `{error}` key, the
/// backend's contract for a permanent rejection on a 200.
bool _isErrorBody(http.Response response) {
if (response.body.isEmpty) {
return false;
}
try {
final decoded = json.decode(response.body);
return decoded is Map<String, dynamic> && decoded.containsKey('error');
} on FormatException {
// Non-JSON body, not a structured rejection.
return false;
}
}
}

View File

@@ -38,9 +38,27 @@ void main() {
// Assert
expect(ex.type, ErrorType.json);
expect(ex.errors['foo'], 'bar');
expect(ex.statusCode, 400);
expect(ex.source, ExceptionSource.api);
expect(ex.context, isNull);
expect(ex.toString(), contains('WgerHttpException'));
});
test('carries source and context when provided', () {
final resp = http.Response('{"error":"invalid"}', 200);
final ex = WgerHttpException(
resp,
source: ExceptionSource.powersync,
context: {'table': 'manager_routine', 'op': 'put'},
);
expect(ex.source, ExceptionSource.powersync);
expect(ex.statusCode, 200);
expect(ex.context, {'table': 'manager_routine', 'op': 'put'});
expect(ex.errors['error'], 'invalid');
});
test('falls back on malformed JSON', () {
// Arrange
const body = '{"foo":';
@@ -102,6 +120,8 @@ void main() {
// Assert
expect(ex.type, ErrorType.json);
expect(ex.errors, map);
expect(ex.source, ExceptionSource.api);
expect(ex.statusCode, isNull);
});
});
}

View File

@@ -30,9 +30,9 @@ import 'connector_test.mocks.dart';
@GenerateMocks([ApiClient])
void main() {
// A rejected upload calls showGeneralErrorDialog, which reads
// navigatorKey.currentContext. Initialising the binding makes that return
// null (no widget tree) so the dialog is skipped instead of throwing.
// A rejected upload surfaces via handleError -> showGeneralErrorDialog, which
// reads navigatorKey.currentContext. Initialising the binding makes that
// return null (no widget tree) so the dialog is skipped instead of throwing.
TestWidgetsFlutterBinding.ensureInitialized();
late DjangoConnector connector;
@@ -300,5 +300,51 @@ void main() {
// Not completed: the op stays queued for PowerSync to retry once online.
expect(completed, isFalse);
});
test('rethrows RetryableUploadException on transient/retryable statuses', () async {
// Server errors, gateway timeout, rate limiting and a non-recoverable 401
// are retried: throw so PowerSync keeps the transaction queued. Mirrors
// the ClientException test above.
for (final status in [500, 502, 503, 504, 408, 429, 401]) {
completed = false;
when(api.upsert(any)).thenAnswer((_) async => http.Response('', status));
await expectLater(
conn.processTransaction(
txWith(CrudEntry(1, UpdateType.put, 'manager_routine', 'r1', 1, {'name': 'x'})),
),
throwsA(isA<RetryableUploadException>()),
reason: 'status $status should be retried',
);
expect(completed, isFalse, reason: 'status $status must stay queued');
}
});
test('reports and completes on unexpected permanent client errors', () async {
// Retrying these would not help, so the op is surfaced and discarded
// rather than blocking the queue. 403 is here, not in the retry set: the
// backend delivers ownership refusals as 200 + {error}, so a real 403 is
// a permanent refusal.
for (final status in [400, 403, 404, 409, 422]) {
completed = false;
when(api.upsert(any)).thenAnswer((_) async => http.Response('', status));
await conn.processTransaction(
txWith(CrudEntry(1, UpdateType.put, 'manager_routine', 'r$status', 1, {'name': 'x'})),
);
expect(completed, isTrue, reason: 'status $status must not block the queue');
}
});
test('completes on a 2xx with an empty body', () async {
when(api.upsert(any)).thenAnswer((_) async => http.Response('', 200));
await conn.processTransaction(
txWith(CrudEntry(1, UpdateType.put, 'manager_routine', 'r1', 1, {'name': 'x'})),
);
expect(completed, isTrue);
});
});
}