Custom Exception in scala

前端 未结 7 840
你的背包
你的背包 2020-12-24 12:02

how can i create custom exceptions in Scala extending Exception class and throw them when exception occurs as well as catch them.

example in java :

7条回答
  •  轮回少年
    2020-12-24 12:39

    Adding to all the answers above, If at all you want to have an error hierarchy, abstract class would help.

    abstract class GenericError(message: String) extends Exception(message)
    
    case class SpecificErrorA(message: String) extends GenericError(message)
    
    case class SpecificErrorB(message: String) extends GenericError(message)
    
    
    throw new SpecificErrorA("error on A") OR throw new SpecificErrorB("error on B")
    

    The same is possible using trait instead of an abstract class but they are limited in that they do not have constructor parameters.

    Probably use GenericError everywhere and deconstruct (pattern match) it on the application/controller boundary.

提交回复
热议问题