scala - 如何处理 'Configuration error[Cannot connect to database [...]]'

标签 scala error-handling playframework database-connection

我正在使用 Play 框架实现一个使用多个数据库的 Web 服务。所有数据库都通过指定 db.database1...、db.database2... 属性在 conf/application.conf 中进行配置。

启动时,play会尝试与数据库中配置的所有数据库建立连接,如果一个连接失败,该服务将不会启动。

就我而言,并非所有数据库都是启动 Web 服务所必需的,但如果某些数据库不可用,Web 服务仍然可以以有限的功能运行。由于并非所有数据库都在我的控制之下,因此我的 Web 服务处理连接错误至关重要。

因此我的问题:

有没有办法实现

  1. 通过重写某些“onError”方法或在正确的位置插入 try-catch 来处理连接错误,或者
  2. 在运行时手动创建数据源以处理创建时的错误

我更喜欢解决方案 2。

我正在使用 play 版本 2.4.2 和 scala 版本 2.11.7。

由于整个异常填充了多个页面,因此我只在此处插入第一行:

CreationException: Unable to create injector, see the following errors:

1) Error in custom provider, Configuration error: Configuration error[Cannot connect to database [foo]]
  while locating play.api.db.DBApiProvider
  while locating play.api.db.DBApi
    for field at play.api.db.NamedDatabaseProvider.dbApi(DBModule.scala:80) 
  while locating play.api.db.NamedDatabaseProvider 
  at com.google.inject.util.Providers$GuicifiedProviderWithDependencies.initialize(Providers.java:149) 
  at play.api.db.DBModule$$anonfun$namedDatabaseBindings$1.apply(DBModule.scala:34): 
Binding(interface play.api.db.Database qualified with QualifierInstance(@play.db.NamedDatabase(value=appstate)) to ProviderTarget(play.api.db.NamedDatabaseProvider@1a7884c6)) (via modules: com.google.inject.util.Modules$OverrideModule -> play.api.inject.guice.GuiceableModuleConversions$$anon$1) 
Caused by: Configuration error: Configuration error[Cannot connect to database [foo]] 
    at play.api.Configuration$.configError(Configuration.scala:178)
    at play.api.Configuration.reportError(Configuration.scala:829) 
    at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:48) 
    at play.api.db.DefaultDBApi$$anonfun$connect$1.apply(DefaultDBApi.scala:42) 
    at scala.collection.immutable.List.foreach(List.scala:381) 
    at play.api.db.DefaultDBApi.connect(DefaultDBApi.scala:42) 
    at play.api.db.DBApiProvider.get$lzycompute(DBModule.scala:72)

最佳答案

我记得存在一个全局设置配置文件,用于在应用程序启动时捕获错误。

看这里:https://www.playframework.com/documentation/2.0/ScalaGlobal我知道您正在使用更新的游戏版本,但您会更全面地了解它的工作原理。

在 2.4.x 版本中,此文件已被删除并现在使用 DI ( https://www.playframework.com/documentation/2.4.x/GlobalSettings )。

关于scala - 如何处理 'Configuration error[Cannot connect to database [...]]',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32692076/

相关文章:

java - 每一步后检查错误值

c# - 启用自定义错误会创建运行时错误

scala - 如何在不显式映射结果的情况下转发 WSResponse

playframework - 执行 Play 运行时 Play Framework 报错java.lang.NoSuchMethodError

mysql - Slick flatMap 不会将所有查询作为一个组执行

javascript - 从 Scala.js 访问 JS this

java - 变形金刚 : FAILURE: Build failed with an exception

scala - Scala 中这两个代码片段有什么区别

scala - Scala 中的错误处理

java - 错误 : package com. sun.tools.javac.util 不存在