Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Device Sync - Flutter SDK

Gestionar errores de sincronización - SDK de Flutter

Al desarrollar una aplicación que utiliza Sincronización de dispositivos: debe configurar un controlador de errores. Este controlador detectará y responderá a cualquier llamada a la API relacionada con la sincronización fallida.

Agregar un syncErrorHandlerpropiedad a FlexibleSyncConfiguration al crear un reino sincronizado. syncErrorHandler Es una función de devolución de llamada SyncErrorHandler. SyncErrorHandler acepta un SyncError como parámetro. Siempre que SyncError se produce un en el dominio, se invoca la función de devolución de llamada con el SyncError como argumento.

final config = Configuration.flexibleSync(currentUser, [Car.schema],
syncErrorHandler: (SyncError error) {
print("Error message${error.message}");
});
final realm = Realm(config);

Si no especifica un syncErrorHandler, el comportamiento predeterminado es imprimir el SyncError en la consola.

Tip

For a list of common Device Sync errors and how to handle them, refer to Sync Errors in the App Services Device Sync documentation.

As of Realm Flutter SDK v1.3, you can get detailed information about compensating write errors.

void handleCompensatingWrite(
CompensatingWriteError compensatingWriteError) {
final writeReason = compensatingWriteError.compensatingWrites!.first;
print("Error message: ${writeReason.reason}");
// ... handle compensating write error as needed.
}
final config = Configuration.flexibleSync(currentUser, [Car.schema],
syncErrorHandler: (syncError) {
if (syncError is CompensatingWriteError) {
handleCompensatingWrite(syncError);
}
});
final realm = Realm(config);

For more details, refer to the CompensatingWriteError class reference documentation.

When using Device Sync, a client reset is an error recovery task that your client app must perform when the Device Sync server can no longer sync with the client realm.

Clients in this state may continue to run and save data locally but cannot send or receive sync changesets until they perform a client reset. The client must reset its realm to a state that matches the server in order to restore the ability to sync. The unsyncable realm on the client may contain data that has not yet synced to the server.

The Realm SDK can attempt to recover or discard that data during the client reset process. The Realm SDK provides methods to automatically handle client resets in most scenarios.

Para obtener más información sobre qué puede causar un restablecimiento del cliente, consulta Restablecimientos de clientes en la documentación de App Services.

To manage the client reset process, you can specify a client reset mode in your FlexibleSyncConfiguration.clientResetHandler property when configuring a realm. You can use the following client reset modes:

  • Modo de recuperación o descarte de cambios no sincronizados (predeterminado): En este modo de restablecimiento del cliente, el controlador de restablecimiento del cliente primero intenta recuperar los cambios no sincronizados. Si la recuperación falla, este controlador recurre al modo de descarte de cambios no sincronizados, que elimina todos los cambios locales no sincronizados. Si este modo falla, el controlador recurre al modo de recuperación manual.

  • Recover unsynced changes mode: In this client reset mode, the client reset handler first attempts to recover unsynced changes. If recovery fails, this handler falls back to manual recovery mode.

  • Descartar el modo de cambios no sincronizados: Este modo de restablecimiento del cliente elimina permanentemente todos los cambios locales no sincronizados realizados desde la última sincronización exitosa. Si la recuperación falla, este controlador recurre a un modo de recuperación manual.

  • Manual recovery mode: This client reset mode provides a way for you to implement your own recovery strategy.

The following sections describe how to use these client reset modes.

The Realm SDKs provide client reset modes that automatically handle most client reset errors.

Los modos automáticos de restablecimiento del cliente restauran tu archivo Realm local a un estado de sincronización sin cerrar el realm o perder notificaciones. Los siguientes modos de restablecimiento del cliente admiten restablecimientos automáticos del cliente:

  • Recuperar el modo de cambios no sincronizados

  • Recover or discard unsynced changes mode

  • Discard unsynced changes mode

The differences between these modes are based on how they handle changes on the device that have not yet synced to the backend. Only manual recovery mode does not perform an automatic client reset.

Choose recover unsynced changes mode to handle most client reset scenarios automatically. This attempts to recover unsynced changes when a client reset occurs.

If your app requires specific client reset logic that can't be handled automatically, you may want or need to add a manual client reset handler to the automatic client reset mode.

Client Recovery is a feature that is enabled by default when you configure Device Sync. When Client Recovery is enabled, Realm automatically manages the client reset process in most cases. When you make schema changes the client can recover unsynced changes when there are no schema changes, or non-breaking schema changes.

To use Client Recovery, configure your realm with recover unsynced changes or recover or discard unsynced changes client reset modes.

Cuando la Recuperación de Cliente está habilitada, estas reglas determinan cómo se integran los objetos, incluyendo la resolución de conflictos cuando tanto el backend como el cliente realizan cambios en el mismo objeto:

  • Objects created locally that were not synced before client reset are synced.

  • Si se elimina un objeto en el servidor, pero se modifica en el cliente en recuperación, la eliminación tiene prioridad y el cliente descarta la actualización.

  • If an object is deleted on the recovering client, but not the server, then the client applies the server's delete instruction.

  • En el caso de actualizaciones conflictivas en el mismo campo, se aplica la actualización del cliente.

Para obtener más información sobre cómo configurar la Recuperación de cliente, consulte Recuperación de cliente en la documentación de Servicios de aplicaciones.

La recuperación del cliente no se puede realizar cuando la aplicación realiza cambios importantes en el esquema. Un cambio importante es un cambio que se puede realizar en el esquema del servidor y que requiere una acción adicional para su gestión. En este caso, el cliente se reinicia con un recurso de respaldo manual tras un error.

Para obtener información sobre cambios de esquema disruptivos y no disruptivos, consulte Referencia rápida sobre cambios disruptivos y no disruptivos en la documentación de App Services.

El modo "Recuperar o descartar cambios no sincronizados" intenta recuperar automáticamente todos los cambios locales no sincronizados durante el restablecimiento del cliente. Si no se especifica un modo de restablecimiento, el comportamiento predeterminado es recuperar o descartar los cambios no sincronizados. Si el proceso de recuperación automática falla, se recurre al modo "Descartar cambios no sincronizados". Si este proceso falla, se recurre de nuevo al modo de restablecimiento manual.

Recover or discard unsynced changes mode provides the most robust recovery process. However, do not use recover or discard unsynced changes mode if your application cannot lose local data that has not yet synced to the backend.

To customize usage of recover or discard unsynced changes mode, pass a RecoverOrDiscardUnsyncedChangesHandler callback to the Configure.clientResetHandler. Add the following optional callback methods to extend the handler's functionality:

  • onBeforeReset, que el SDK invoca antes del restablecimiento del cliente. Puedes usar esta función de retorno para notificar al usuario antes de que comience el restablecimiento del cliente.

  • onAfterRecovery, que el SDK invoca si y solo si se completa correctamente el restablecimiento automático. Se puede usar para notificar al usuario que el restablecimiento del cliente está completo.

  • onAfterDiscard, que el SDK invoca solo si falla el restablecimiento automático del cliente y la estrategia local de descarte tiene éxito. Si la estrategia de descarte falla, no se invoca esta devolución de llamada.

  • onManualResetFallback, which the SDK invokes only if the automatic recovery and the discard strategy have failed. Implement this callback to handle the reset failure, as explained in the Manual Recovery Fallback section.

El siguiente ejemplo muestra el uso de RecoverOrDiscardUnsyncedChangesHandler y cada una de sus funciones de retorno:

final config = Configuration.flexibleSync(currentUser, schema,
clientResetHandler: RecoverOrDiscardUnsyncedChangesHandler(
// All the following callbacks are optional
onBeforeReset: (beforeResetRealm) {
// Executed before the client reset begins.
// Can be used to notify the user that a reset is going
// to happen.
},
onAfterRecovery: (beforeResetRealm, afterResetRealm) {
// Executed if and only if the automatic recovery has succeeded.
},
onAfterDiscard: (beforeResetRealm, afterResetRealm) {
// Executed if the automatic recovery has failed
// but the discard unsynced changes fallback has completed
// successfully.
},
onManualResetFallback: (clientResetError) {
// Automatic reset failed. Handle the reset manually here.
// Refer to the "Manual Client Reset Fallback" documentation
// for more information on what you can include here.
},
));

Recover unsyced changes mode attempts to recover all unsynced local changes automatically during a client reset. However, unlike recover or discard unsyced changes mode, this mode does not fall back to a discard local changes if the automatic recovery fails. Instead, it falls back to manually recover changes.

Para utilizar el modo de recuperación de cambios no sincronizados, pasa una función de RecoverUnsyncedChangesHandler de retorno al Configure.clientResetHandler. Este handler proporciona los siguientes métodos de funciones de retorno:

  • onBeforeReset, which the SDK invokes prior to the client reset. You can use this callback to notify the user before the reset begins.

  • onAfterReset, que el SDK invoca si y solo si la restauración automática se completa con éxito. Puedes utilizar esta función de retorno para notificar al usuario cuando la restauración se haya completado correctamente.

  • onManualResetFallback, que el SDK invoca solo si la recuperación automática y la estrategia de descarte fallan. Esta devolución de llamada se implementa para gestionar el error de restablecimiento, como se explica en la sección "Respaldo de recuperación manual".

El siguiente ejemplo muestra el uso de RecoverUnsyncedChangesHandler y cada una de sus funciones de retorno:

final config = Configuration.flexibleSync(currentUser, schema,
clientResetHandler: RecoverUnsyncedChangesHandler(
// All the following callbacks are optional
onBeforeReset: (beforeResetRealm) {
// Executed before the client reset begins.
// Can be used to notify the user that a reset is going
// to happen.
},
onAfterReset: (beforeResetRealm, afterResetRealm) {
// Executed after the client reset is complete.
// Can be used to notify the user that the reset is done.
},
onManualResetFallback: (clientResetError) {
// Automatic reset failed. Handle the reset manually here.
// Refer to the "Manual Client Reset Fallback" documentation
// for more information on what you can include here.
},
));

Discard unsyced changes mode permanently deletes all local unsynced changes made since the last successful sync. If you choose to use this client reset mode, the SDK restores your local realm file to a syncable state without closing the realm and while keeping notifications fully working. If this process fails, it falls back to manual recovery mode.

Do not use recover or discard unsynced changes mode if your application cannot lose local data that has not yet synced to the backend.

To use discard unsynced changes mode, pass a DiscardUnsyncedChangesHandler callback to the Configure.clientResetHandler. This handler provides the following callback methods:

  • onBeforeReset, which the SDK invokes prior to the client reset. You can use this callback to notify the user before the reset begins.

  • onAfterReset, which the SDK invokes if and only if the reset completes successfully. You can use it to notify the user when the reset is complete.

  • onManualResetFallback, which the SDK invokes only if the automatic recovery and the discard strategy have failed. You implement this callback to handle the reset failure, as explained in the Manual Recovery section.

El siguiente ejemplo muestra el uso de DiscardUnsyncedChangesHandler y cada una de sus funciones de retorno:

final config = Configuration.flexibleSync(currentUser, schema,
clientResetHandler: DiscardUnsyncedChangesHandler(
onBeforeReset: (beforeResetRealm) {
// Executed before the client reset begins.
// Can be used to notify the user that a reset is going
// to happen.
},
onAfterReset: (beforeResetRealm, afterResetRealm) {
// Executed after the client reset is complete.
// Can be used to notify the user that the reset is done.
},
onManualResetFallback: (clientResetError) {
// Automatic reset failed. Handle the reset manually here.
// Refer to the "Manual Client Reset Fallback" documentation
// for more information on what you can include here.
},
));

Si el restablecimiento del cliente con recuperación no se puede completar automáticamente, como cuando hay cambios de esquema importantes, el proceso de restablecimiento del cliente se deriva a un gestor de errores manual. Esto puede ocurrir en cualquiera de los modos de restablecimiento automático del cliente:

  • Recuperar el modo de cambios no sincronizados

  • Recover or discard unsynced changes mode

  • Discard unsyced changes mode

You must provide a manual client reset implementation in the onManualResetFallback callback of the client reset handler for these modes.

In onManualResetFallback, initiate a client reset using the ClientResetError.resetRealm() method of the ClientResetError parameter of the callback. ClientResetError.resetRealm() performs a client reset by deleting the realm on device and downloading relevant data from the server. Before you use this method, you must close all instances of the realm that you are resetting.

The following example demonstrates how you can manually handle an error case by discarding all unsynced changes:

// Lazily initialize `realm` so that it can be used in the callback
// before the realm has been opened.
late Realm realm;
final config = Configuration.flexibleSync(currentUser, schema,
// This example uses the `RecoverOrDiscardUnsyncedChangesHandler`,
// but the same logic could also be used with the `RecoverUnsyncedChangesHandler`
// or the `DiscardUnsyncedChangesHandler`.
clientResetHandler: RecoverOrDiscardUnsyncedChangesHandler(
onManualResetFallback: (clientResetError) {
// Prompt user to perform a client reset immediately. If they don't,
// they won't receive any data from the server until they restart the app
// and all changes they make will be discarded when the app restarts.
var didUserConfirmReset = showUserAConfirmationDialog();
if (didUserConfirmReset) {
// You must close the Realm before attempting the client reset.
realm.close();
// Attempt the client reset.
try {
clientResetError.resetRealm();
// Navigate the user back to the main page or reopen the
// the Realm and reinitialize the current page.
} catch (err) {
// Reset failed.
// Notify user that they'll need to update the app
}
}
},
));

Usa el modo de recuperación manual para los casos poco habituales en los que necesitas personalizar el proceso de recuperación de datos. En la mayoría de los casos, debes utilizar una de las otras estrategias para el restablecimiento del cliente. Puedes querer usar un gestor de restablecimiento manual del cliente si la lógica de recuperación automática no funciona para tu aplicación y no puedes descartar los datos locales no sincronizados.

To use manual recovery mode, pass a ManualRecoveryHandler callback to the Configure.clientResetHandler.

El controlador proporciona la devolución de llamada onManualReset, que permite restablecer el cliente. onManualReset En, inicie un restablecimiento del cliente mediante el método ClientResetError.resetRealm() del ClientResetError parámetro de la devolución de llamada. ClientResetError.resetRealm() realiza un restablecimiento del cliente eliminando el dominio en el dispositivo y descargando los datos relevantes del servidor. Antes de usar este método, debe cerrar todas las instancias del dominio que se está restableciendo.

// Lazily initialize `realm` so that it can be used in the callback
// before the realm has been opened.
late Realm realm;
final config = Configuration.flexibleSync(currentUser, schema,
clientResetHandler: ManualRecoveryHandler((clientResetError) {
// You must close the Realm before attempting the client reset.
realm.close();
// Handle manual client reset here...
// Then perform the client reset.
clientResetError.resetRealm();
}));

Puede probar manualmente el manejo de restablecimiento del cliente de su aplicación finalizando y volviendo a habilitar la sincronización del dispositivo.

When you terminate and re-enable Sync, clients that have previously connected with Sync are unable to connect until after they perform a client reset. Terminating Sync deletes the metadata from the server that allows the client to synchronize. The client must download a new copy of the realm from the server. The server sends a client reset error to these clients. So, when you terminate Sync, you trigger the client reset condition.

To test client reset handling:

  1. Write data from a client application and wait for it to synchronize.

  2. Termina y vuelve a habilitar Device Sync.

  3. Ejecuta la aplicación cliente nuevamente. La aplicación debería obtener un error de restablecimiento del cliente cuando intente conectarse al servidor.

Advertencia

Mientras itera sobre la gestión del restablecimiento de clientes en su aplicación cliente, es posible que tenga que finalizar y volver a habilitar la sincronización repetidamente. Esto impide que todos los clientes existentes puedan sincronizar hasta después de completar un restablecimiento. Para evitar esto en producción, pruebe la gestión del restablecimiento de clientes en un entorno de desarrollo.

Volver

Sincronizar múltiples procesos

En esta página