sfackler / r2d2

A generic connection pool for Rust
Apache License 2.0
1.51k stars 82 forks source link

How to catch and handle connection issues? #79

Closed volfco closed 5 years ago

volfco commented 5 years ago

I have two cases where I would like to catch and handle the fact that my DB is down.

  1. When the application starts up I want to throw an error an exist
  2. During a Request, I want to return an error saying the DB is down.

In both cases, as far as I can tell, there is no way for me to catch the error and gracefully handle it.

let manager = PostgresConnectionManager::new(config.db_uri.unwrap(), TlsMode::None).unwrap();
let pool = r2d2::Pool::new(manager).unwrap();
...
let conn = pconn.get().unwrap();
let request_query = format!("SELECT ... LIMIT 1;");
let request_rcon = conn.query(&request_query, &[]);
if request_rcon.is_err() {
...
}

I would expect the conn.query to return an error that I can catch when there is a connection issue but it doesn't. In both cases, it spins dumping the following to console:

 ERROR r2d2 > IO error: Connection refused (os error 111)
 ERROR r2d2 > IO error: Connection refused (os error 111)
 ERROR r2d2 > IO error: Connection refused (os error 111)
 ERROR r2d2 > IO error: Connection refused (os error 111)
 ERROR r2d2 > IO error: Connection refused (os error 111)

I would love a way where I can gracefully catch and handle this error, and not have the application hang.

sfackler commented 5 years ago
  1. Pool::new will return an error if it's unable to create all of the required connections before the configured timeout.
  2. pool.get() will return an error if it's unable to obtain a connection before the configured timeout.
volfco commented 5 years ago

Yep. Configuring the connection_timeout fixes both. It might be useful to document this.

Thanks!