目前,我编写了多个自定义异常用例类,用于抛出异常消息。在自定义异常中,除了名称之外,所有内容都是相同的。有没有办法动态地将异常消息传递给一个类。这样我就可以避免编写多个case类。有没有更好的方法来实现这个场景?任何建议。
示例:
// case class
// Custom Exception-1
final case class MissingRule(private val message: String = "",
private val cause: Throwable = None.orNull)
extends Exception(message, cause)
// Custom Exception-2
final case class MissingPrimaryKey(private val message: String = "",
private val cause: Throwable = None.orNull)
extends Exception(message, cause)Object sampleObj {
def process(){
try {
if (some condition){
throw MissingRule ("Rule Missing")
}
if (some conition){
throw MissingPrimaryKey ("Key is Missing")
}
} catch {
// Here I am throwing the exception again
// so that the spark job will fail with proper error message
case _: MissingRule =>
throw MissingRule("Rule Missing")
case _: MissingPrimaryKey =>
throw MissingPrimaryKey("Key is Missing")
case e: Exception =>
println("Exception: " + e.printStackTrace().toString)
} finally {
// some operation
}
}
}发布于 2018-12-07 05:51:02
我不确定您在这里试图实现的是什么。
如果你不想创建多个类,只创建一个类,并且总是用不同的消息抛出它:
case class MyCoolException(message: String) extends Exception(message)或者,反过来,如果您想要不同的类,但又不想为它们指定消息(有点道理),那么只需使用这些消息作为默认值,而不是"":
case class MissingRule(message: String = "Rule is missing") extends Exception(message)
case class MissingKey(message: String = "Key is missing") extends Exception(message)等等..。
https://stackoverflow.com/questions/53659443
复制相似问题