Exceptions.kt

  1. package com.hexagonkt.core

  2. import com.hexagonkt.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 by lazy {
  8.     try {
  9.         assert(false)
  10.         false
  11.     } catch (_: AssertionError) {
  12.         true
  13.     }
  14. }

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

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

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