Realm Sync broken after deleting user account

In my app, I use anonymous authentication to let user access public static data without having to create an account. I have set up a trigger to regularly delete anonymous users to cleanup the database. The anonymous users can also be deleted after 90 days, according to the doc.

The problem is that, after deleting an anonymous user account, when the user opens the app again, the following error occurs:

2021-02-01 18:24:32.305629+0100 App[3170:1683819] Sync: Connection[1]: Websocket: Expected HTTP response 101 Switching Protocols, but received:

HTTP/1.1 401 Unauthorized

cache-control: no-cache, no-store, must-revalidate

connection: close

content-length: 190

content-type: application/json

date: Mon, 01 Feb 2021 17:24:32 GMT

server: envoy

vary: Origin

x-envoy-max-retries: 0

x-frame-options: DENY

2021-02-01 18:24:32.305722+0100 App[3170:1683819] Sync: Connection[1]: Connection closed due to error

And on the server logs, an InvalidSession error is thrown. After this, the client can’t sync anymore to the server.

How can I “catch” this error and just make the user login anonymously again when that happens?

Are you able to check app.currentUser and check if it is not null. If it is, then try to log in another anonymous user again?