How to catch core data 'constraint violation' Xcode8/iOS10

267 Views Asked by At

I have a small code set that captures data messages from a monitoring device. The messages contain a date/time field (startDts) that is unique. I am storing these with core data to a sqlite database. I have set up a constraint for startDts. All goes well until I receive a message with startDts I have already received before - I get a 'Contraint violation' when attempting to save. Makes sense.

My problem is that I don't seem to be able to catch it in code. In stead, the debugger just stops on the 'try' line.

let we = WaterEvent(context: self.coreDataStack.context)
we.startDts = e.startTime as NSDate?
we.stopDts  = e.endTime as NSDate?

do {
    try self.coreDataStack.context.save()     // << Xcode breaks here on constraint violation
}
catch {
    let nserror = error as NSError
    print("CoreDataStack Unresolved error \(nserror), \(nserror.userInfo)")
    print("Constraint violation for: \(we.startDts)")  
}

So the 'catch' code block is never executed i.e., I cannot truly respond to the constraint violation intelligently.

This is a snapshot of the debugger output: enter image description here First three lines are print statements from my code, line 4 & 5 is debugger output.

So what's going on? Is the 'Constraint violation' not a thrown exception?

0

There are 0 best solutions below