Skip to main content
1 of 3

IsDatabaseUp returns true or throws exception

I want to write an ASP.NET Web API endpoint that allows clients to check if database is running.

The method below is check if database is up by establishing a connection and running a dummy sql statement. If exception is thrown, the database is down. Thus, it always return true when it is up.

public interface IDatabaseHealthStatus {
  bool IsDatabaseUp();
}

public class DatabaseHealthStatus :IDatabaseHealthStatus {

public bool IsDatabaseUp(){

  using(var con = new SqlConnection(connectionString)
  using(var cmd= new SqlCommand("SELECT 1", con)
  {
      con.Open();
     cmd.ExecuteReader();
     return true;  //always returns true, unless exception throws
  }    
}    

}

The calling method looks like below.

API controller action method:

[HttpGet]
public IHttpActionResult IsDatabaseUp(){

  databaseHealthStatus.IsDatabaseUp(); //return value is ignored. Exception is handled by global exception handler, if any
  return OK();

}

Questions:

1: IsDatabaseUp() returns boolean type, but it always returns true (not false), unless it throws exception, which might be confusing (that is, bool, only returns true, and exception). I don't want to catch exception within the method, and return false. Because I want global exception handler to handle it and log the exception. This way it makes the code cleaner by reducing try/catch block. But in this case, unless comment is put for the method, it might be confusing.

Is this the best way to return the result? What do you think?