我是 Scala - http4s 初学者。
我必须使用 Scala 和 http4s 为我的工作创建一个 MVC 应用程序,但我面临以下问题:
我无法捕获存储库内的 mongo 驱动程序异常
我的任务之一是为某些请求创建新数据库,因此我开始在存储库中设计“createDatabase”函数。
根据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
所以我的代码是:
def createDatabase(databaseName: String) = {
IO.fromFuture(IO {
MongoClient("con_string").getDatabase(databaseName).createCollection("any_name").head()
})
}
预计将创建一个包含名称为“any_name”的集合的新数据库。
如果使用已存在的数据库名称调用createDatabase,操作将失败,并在控制台中输出:
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"}
我尝试使用 try {} catch、Try {}、withRecover() 等,希望捕获此异常并以异常消息响应,但没有任何效果。
一些例子:
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)
}
})
}
由于保密工作协议(protocol),一些片段被混淆了。
请帮我。
谢谢!
最佳答案
使用尝试
解决了问题
def createDatabase(databaseName: String) = {
IO.fromFuture(IO {
MongoClient("con_string").getDatabase(databaseName).createCollection("any_name").head()
}).attempt
}
但是,无论发生什么,错误消息似乎都是由 DEBUG 级别的记录器打印的。所以我也将日志记录级别更改为INFO。
Logger.getRootLogger.setLevel(Level.INFO)
关于mongodb - Scala 的 MongoDriver + http4s : How to check if createCollection() throws an exception?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68406578/