Pradeep
Pradeep

Reputation: 303

How to pass error message dynamically to a custom exception in scala

Currently I wrote multiple custom exception case class for throwing exception message. Here in the custom exception everything is same except the name. Is there a way to pass the exception message dynamically to only one class. In that way I can avoid writing multiple case class. Is there a better way to implement the scenario? Any suggestion. Purpose of throwing the custom message in the catch block is to fail the spark job with proper exception message.

Example:

// 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)

Here is the actual implementation

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
  }
 }
}

Upvotes: 0

Views: 1313

Answers (1)

Dima
Dima

Reputation: 40500

I am not sure what it is you are trying to achieve here.

If you don't want to create multiple classes, make just one, and always throw that with different messages:

case class MyCoolException(message: String) extends Exception(message)

Or, the other way around, if you want different classes, but don't want to have to specify messages to them (kinda makes sense), then just use those messages as defaults instead of "":

 case class MissingRule(message: String = "Rule is missing") extends Exception(message)     
 case class MissingKey(message: String = "Key is missing") extends Exception(message)

etc. ...

Upvotes: 1

Related Questions