Exceptions.kt

  1. package com.hexagontk.core

  2. import com.hexagontk.core.text.eol

  3. /**
  4.  * This flag is true when assertions are enabled in the JVM (`-ea` flag). Assertions are disabled by
  5.  * default in the JVM, but they are enabled (and should be that way) on the tests.
  6.  */
  7. val assertEnabled: Boolean =
  8.     try {
  9.         assert(false)
  10.         false
  11.     } catch (_: AssertionError) {
  12.         true
  13.     }

  14. /** Syntax sugar to throw errors. */
  15. val fail: Nothing
  16.     get() = error("Invalid state")

  17. /**
  18.  * Return the stack trace array of the frames that starts with the given prefix.
  19.  *
  20.  * @receiver Throwable which stack trace will be filtered.
  21.  * @param prefix Prefix used to filter stack trace elements (applied to class names).
  22.  * @return Array with the frames of the throwable whose classes start with the given prefix.
  23.  */
  24. fun Throwable.filterStackTrace(prefix: String): Array<out StackTraceElement> =
  25.     if (prefix.isEmpty())
  26.         this.stackTrace
  27.     else
  28.         this.stackTrace.filter { it.className.startsWith(prefix) }.toTypedArray()

  29. /**
  30.  * Return this throwable as a text.
  31.  *
  32.  * @receiver Throwable to be printed to a string.
  33.  * @param prefix Optional prefix to filter stack trace elements.
  34.  * @return The filtered (if filter is provided) Throwable as a string.
  35.  */
  36. fun Throwable.toText(prefix: String = ""): String =
  37.     "${this.javaClass.name}: ${this.message}" +
  38.     this.filterStackTrace(prefix).joinToString(eol, eol) { "\tat $it" } +
  39.     if (this.cause == null) ""
  40.     else "${eol}Caused by: " + (this.cause as Throwable).toText(prefix)