I'm a Scala - http4s beginner.
I have to create a MVC application for my job using Scala with http4s and I'm facing the following problem :
One of my tasks is to create new databases for some requests so I started to design the function "createDatabase" inside my Repository.
According to the documentation :
MongoDatabase instance provides methods to interact with a database but the database might not actually exist and will only be created on the insertion of data via some means; e.g. the creation of a collection or the insertion of documents
so my code is :
def createDatabase(databaseName: String) = {
IO.fromFuture(IO {
MongoClient("con_string").getDatabase(databaseName).createCollection("any_name").head()
})
}
expecting that a new database that contains collection with name "any_name" will be created.
If createDatabase is called with a database name that already exists, the operation will fail, outputting in console :
com.mongodb.MongoCommandException: Command failed with error 48 (NamespaceExists): 'Collection already exists. NS: NewDbTest.customers' on server localhost:27017. The full response is {"ok": 0.0, "errmsg": "Collection already exists. NS: NewDbTest.customers", "code": 48, "codeName": "NamespaceExists"}
I tried to use try {} catch, Try {}, withRecover(), and many more, hoping to catch this exception and respond with exception message, but nothing worked.
Some example:
def createDatabase(databaseName: String) = {
IO.fromFuture(IO {
try {
MongoClient("con_string").getDatabase(databaseName).createCollection("any_name").head()
}
catch {
case e: MongoCommandException => println("we have exception")
Future.successful(e.getErrorMessage)
}
})
}
def createDatabase(databaseName: String) = {
IO.fromFuture(IO {
client.getDatabase(databaseName).createCollection("any_name").map(operation => Try {operation}).head()
})
}
def createDatabase(databaseName: String) = {
IO.fromFuture(IO {
client.getDatabase(databaseName).createCollection("any_name").head() recover {
case exception: Exception => Future.successful(exception.getMessage)
}
})
}
Some snippets were obfuscated due to the confidential job agreement.
Please help me.
Thank you !
Tackled the problem using atempt
def createDatabase(databaseName: String) = {
IO.fromFuture(IO {
MongoClient("con_string").getDatabase(databaseName).createCollection("any_name").head()
}).attempt
}
However, it seems that the error message is printed by logger at DEBUG level, no matter what happens. So I also changed the logging level to INFO.
Logger.getRootLogger.setLevel(Level.INFO)