title: Scala: Exception Pattern Matching
body: <p>I need to define an <code>Exception</code> that provides context information... and this information is stored in a <code>Map</code>. To avoid wrong key names, I've defined the following <code>Enumeration</code>:</p>
  
  <pre><code>object ContextValueName extends Enumeration {
  
    type ContextValueName = Value
  
    val Value1 = Value("Value1")
    val Value2 = Value("Value2")
    val ValueN = Value("ValueN")
  
    implicit def toString(name: ContextValueName) = name.toString
  }
  </code></pre>
  
  <p>This is the <code>Exception</code> code:</p>
  
  <pre><code>import ContextValueName._
  
  trait MyException extends RuntimeException {
  
    val errorCode: Int
    val contextValues: Map[ContextValueName, Option[String]]
  }
  
  object MyException {
  
    def apply(
      message: String, _errorCode: Int, _contextValues: Map[ContextValueName, Option[String]]
    ): MyException = new RuntimeException(message) with MyException {
      val errorCode: Int = _errorCode
      val contextValues: Map[ContextValueName, Option[String]] = _contextValues.withDefault(_ =&gt; None)
    }
  
    def unapply(exception: MyException) = {
      if (exception eq null) None
      else Some((
        exception.errorCode,
        exception.contextValues
      ))
    }
  }
  </code></pre>
  
  <p>And finally here is how I handle exceptions of type <code>MyException</code>:</p>
  
  <pre><code>callService("myService").map { result =&gt;
    ...
  }.recover {
    case e@MyException(1, contextValues) =&gt;
      Logger.debug(s"error invoking myService: ${contextValues(Value1).get}")
    case NonFatal(e) =&gt;
      Logger.error(s"unhandled error: ${e.getMessage}")
  }
  </code></pre>
  
  <p>The problem is that the first <code>case</code> statement is never executed even if the thrown exception is like <code>MyException(1, Map(Value1 -&gt; "too busy"))</code>, and execution always falls in the last <code>case</code> statement. Am I missing something?</p>