Handling exceptions in Scala object constructors

2019-05-28 16:38发布

问题:

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


标签: scala lift