Muncken Muncken - 3 months ago 29
Swift Question

Unable to catch `RealmFileException: Realm file decryption failed` exception

I'm relying on an encrypted realm to store certain data in an app written in Swift. Sometimes I face a situation where I delete a given realm and create a new one to ensure that no data will persist between certain states.

I keep track of encryption keys myself, so there is a risk that I unintentionally attempt to decrypt a realm with a wrong encryption key, which raises the following exception:


libc++abi.dylib: terminating with uncaught exception of type realm::RealmFileException: Unable to open a realm at path '/path/to/private.realm': Realm file decryption failed.


Since this means that I have lost the original encryption key, essentially leaving this particular realm useless, I'd like to be able to delete the realm file and start over instead of crashing.

I create the realm as suggested by the docs:

do {
var configuration = Realm.Configuration.defaultConfiguration
configuration.encryptionKey = ...
try Realm(configuration: configuration)
}
catch let error {

}


I've tried this and similar approaches to catch the
NSException
and return it to be handled by Swift code, but there doesn't seem to be an straight forward way to achieve this. Is it impossible, or am I approaching this incorrectly?

Answer

It turns out the problem was caused by a bug in Realm, where deleteRealmIfMigrationNeeded = true when using encryption, caused the exception to be thrown, but impossible to catch.

From my (very helpful) correspondence with kishikawa katsumi:

The problem that unable to catch error is due to deleteRealmIfMigrationNeeded is true. It changes code flow unintentionally. It seems Realm's bug. We will fix soon.

For now, the only thing to do in my case is to set deleteRealmIfMigrationNeeded = false and handle this case manually. I have filed this issue to Realm.

Update: The issue should be resolved with this commit.