Skip to content

Instantly share code, notes, and snippets.

@billgarrison
Created July 20, 2013 18:52
Show Gist options
  • Save billgarrison/6046064 to your computer and use it in GitHub Desktop.
Save billgarrison/6046064 to your computer and use it in GitHub Desktop.
Function than constructs an NSError from the current SQLite3 engine error state in a thread-safe manner.
NSString *SQLiteErrorDomain = @"SQLiteErrorDomain";
NSError *SQLiteError(sqlite3 *db) {
NSError *error = nil;
if (db) {
/* Lock the database connection to prevent other activity from disturbing the currently recorded internal error code and message.
*/
sqlite3_mutex *mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
if (mutex) {
sqlite3_mutex_enter(mutex);
int lastErrorCode = sqlite3_errcode(db);
const char *lastErrorMessage = sqlite3_errmsg(db);
error = [NSError errorWithDomain:SQLiteErrorDomain code:lastErrorCode userInfo:
@{NSLocalizedDescriptionKey : [NSString stringWithUTF8String:lastErrorMessage]}
];
sqlite3_mutex_leave(mutex);
sqlite3_mutex_free(mutex);
mutex = NULL;
}
}
return error;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment