Question

I defined some class to query a database.

  class SqlGetData {
    ConnectionPool pool;
    List<String> rows;    
    SqlGetData(this.pool);  
    Future <List<String>> run(String sQuery) {
      rows = new List<String>();
      return readData(sQuery).then((_) {
        return rows;
      });
    }
    Future readData(String sQuery) {
      return pool.query(sQuery).then((result) {
        return result.forEach((row) {
          String s = JSON.encode(row);
          rows.add(s);
       });
      });
    }
  }

which I call like this:

  var sql = new SqlGetData(pool);
  sql.run('select firstName, lastName from person where id =' + s1).then((rows) {
    some code here to process the data  
  });  

If the database is not running I get an error on the return pool.query in readData, which I want to catch and pass to the client in some error message. How and where can I code the try ... catch ... to prevent the server from dying? My problem is that I have to return futures, which is still difficult for me to grasp.

Was it helpful?

Solution

Take a look at this article Futures and Error Handling (if you haven't already).

There are two places:

.then((_) => doSomething(), 
      onError: (e) => doErrorHandling()).catchError((e) => doErrorHandling());

OTHER TIPS

Guenter's answer is good. Here are a couple of extra tips.

It's more common to use .catchError() than the named parameter, if in doubt just use .catchError().

One problem with async code is if you forget to add a catchError handler anywhere in your codebase, and an error is triggered, it will bring your whole server down. Not good. However You can use Zones to handle uncaught errors in your code, and prevent this from happening.

There isn't much documentation about Zones at the time of writing, as it is a new feature. Florian Loitsch is working on an article which will appear here sometime soon. Here is an example of using runZoned():

runZoned(() {
  var pool = new Pool.connect(...); // Don't know pool API, just making this up.
  pool.query(sql).then((result) {
     print(result);
  });
  // Oops developer forgot to add a .catchError() handler for the query.
  // .catchError((e) => print('Query error: $e);

}, onError: (e) => print("Uncaught error: $e")); 

This code will run without bringing down your server, despite the missing catchError() handler. Note, you will need to start the pool/connection within the same zone as the query is executed within.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top