1
votes

How exactly do I catch RealmSwift add/delete errors?

i.e.

do {
    try realm.write {
        realm.delete(MyRealmObject())
    }
    completion(true)
} catch {
    completion(false)
}

In this example I've deliberately tried deleting a RealmObject that I've just made up (to make it fail), but it doesn't catch, instead I get this error:

Terminating app due to uncaught exception 'RLMException', reason: 'Can only delete an object from the Realm it belongs to.'

I haven't seen any examples of people handling specific delete/add errors - is there a reason for this?

2

2 Answers

1
votes

Not sure if this is what you're looking for but the following code catches and identifies specific add errors. However, errors accessing different instances of realm are handled differently. So starting with this...

class MyObject: Object {
    @objc dynamic msg = ""
}

do {
    let realm = try Realm()

    let a0 = MyObject()
    a0.msg = "Hello, World"

    try! realm.write {
        realm.add(a0)
    }
} catch let error as NSError {
    print(error.localizedDescription)
}

to then expand.... do the following to ensure the object being deleted matches the realm you are deleting it from.

    do {
        let realm = try Realm()

        if a0.realm == realm {
            try! realm.write {
                realm.delete(a0)
            }
        }
    } catch let error as NSError {
        print(error.localizedDescription)
    }
0
votes

Realm developers extend NSError class with their custom description Can only delete an object from the Realm it belongs to and do FatalError in the predefined list of errors they expect ( may be for a good use of the their library as a help to the developer to correctly use it ) , so they intentionally don't throw an exception that the try can catch