how to catch sqflite DatabaseException in Dart/Flutter
Sounds like the issue got fixed by upgrading to the latest version (don't know which version was used in the reported issue): https://github.com/tekartik/sqflite/issues/17
The SQLException (iOS and Android) is propagated to Dart and can be caught as a DatabaseException using try/catch when using async/await, as shown in the test here: https://github.com/tekartik/sqflite/blob/master/example/lib/exception_test_page.dart#L89-L94
Dan
Updated on November 22, 2022Comments
-
Dan about 1 month
I am unsuccessful at catching an sqflite SQL error that throws a database exception. Note: it's a Future and async.
Sample Code
Future<String> getData() async { Directory documentsDirectory = await getApplicationDocumentsDirectory(); String path = join(documentsDirectory.path, globals.databaseName); Database db = await openDatabase(path); List results = await db.rawQuery("mal formed example of sql on purpose"); }
When I run the code above, rawQuery throws the on-purpose bad SQL. The console shows:
E/SQLiteLog( 7908): (1) near "mal": syntax error
What I want to do is be able to catch SQL errors and handle them.
I've tried .then and .catchError - but not getting it to work.
And from what I've read, normal try {} catch {} doesn't work on Futures. (I did try that to start with... and it didn't work).
try { List results = await db.rawQuery("mal formed example of sql on purpose"); } catch (e) { print(e); }
results in the same error:
E/SQLiteLog( 3148): (1) near "mal": syntax error
-
Günter Zöchbauer almost 5 yearsIf you use
async
/await
you can just usetry
/catch
-
Dan almost 5 yearsI tried that... (as I mentioned in the last sentence above). try { List results = await db.rawQuery("mal formed example of sql on purpose"); } catch (e) { print(e); } returns the same error E/SQLiteLog( 3148): (1) near "mal": syntax error I'm looking for a try catch scenario that works.
-
Günter Zöchbauer almost 5 yearsPlease post the code that shows what you tried
-
Dan almost 5 yearsadded the code in the original post above.
-
Günter Zöchbauer almost 5 yearsLooks like the exception is not propagated to Dart. Don't know how to fix.
-