swift - How to handle error with Realm during writing? -
i'm used working sql database, i'm new realm and, far, i'm impressed ease of use of new mobile database. there don't undestand: how handle error throwing?
take simple example:
i want store in realm db market stocks.
each stock has "symbol" unique identifier: appl apple inc, tsla tesla motors inc, etc.
believe make sense declare these symbols primary keys, since it's not possible have multiple times same symbol in database
when user clicks on symbol (among list of symbols), symbol saved in db.
in raywenderlich tutorial, said: "to simplify code required in tutorial, you’ll used try! when calling realm methods throw error. in own code, should using try , / catch catch errors , handle them appropriately."
so according following pattern:
do { try realm.write { realm.add(symbol) } } catch let error nserror { print("something went wrong: \(error.localizeddescription)") }
so far makes sense.
, if user clicks on symbol in database, (very logically) error:
*** terminating app due uncaught exception 'rlmexception', reason: 'can't set primary key property 'symbol' existing value 'appl'.'
the problem error not catched during run time: i've got crash instead.
my question not how avoid such crash, understand of course it's easy avoid doing simple testing before writing in database :)
my question how in realm catch potential writing errors?
doing wrong?
do/try/catch
in swift catch swift errors, entirely distinct thing objective-c exceptions. realm follows foundation's pattern error reporting: api misuse errors throw exceptions not intended caught (and can't caught in swift), , recoverable errors throw swift errors (or use nserror
out parameters in objective-c).
adding object duplicate primary key considered api misuse, it's fatal error route "handling" fix bug in code. example of recoverable error produce swift error caught catch
running out of disk space while trying save new data.
Comments
Post a Comment