简体   繁体   中英

MongoDriver for Scala + http4s : How to check if createCollection() throws an exception?

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 :

I can't catch mongo driver exceptions inside Repository

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; eg 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM