Handling exceptions in Scala object constructors

馋奶兔 提交于 2019-12-10 11:34:12

问题


I'm trying to use Lift JPA and when I reference Model, it calls the super constructor I'm getting an exception:

object Model extends LocalEMF("LiftPersistenceUnit") with RequestVarEM

The problem is that the exception is hidden behind this exception:

java.lang.NoClassDefFoundError: Could not initialize class...

So, my question is: what is the best way to log/handle exceptions in this case?

Alternatively, can anyone recommend another pattern to use Lift JPA? The way Model has been code is the recommended way, but it's not very user-friendly IMO. The idea is to have a singleton entity manager factory which is accessible via a request variable.sc


回答1:


I can think of the only way to execute something prior to LocalEMF's constructor:

class Model(val init: Unit = println("Hai")) 
  extends LocalEMF("LiftPersistenceUnit") with RequestVarEM

Maybe you could proxy a call to LocalEMF("LiftPersistenceUnit"), and add appropriate logging on exceptions, using some extraordinary trick.

EDIT

I found it:

class LocalEMF(haha: String) { val e = throw new RuntimeException }
trait RequestVarEM

class Model(val init: Unit = println("Hai")) extends { val e = 
  try new LocalEMF("LiftPersistenceUnit") catch {
    case t: Throwable => println("Catched: " + t); throw t
  } 
} with RequestVarEM


来源:https://stackoverflow.com/questions/14114491/handling-exceptions-in-scala-object-constructors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!