run.qontract.core.pattern.ContractException.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of qontract-core Show documentation
Show all versions of qontract-core Show documentation
A Contract Testing Tool that leverages Gherkin to describe APIs in a human readable and machine enforceable manner
package run.qontract.core.pattern
import run.qontract.core.Result
import run.qontract.core.Scenario
import run.qontract.core.resultReport
data class ContractException(val errorMessage: String = "", val breadCrumb: String = "", val exceptionCause: ContractException? = null, val scenario: Scenario? = null) : Exception(errorMessage) {
fun failure(): Result.Failure =
Result.Failure(errorMessage, exceptionCause?.failure(), breadCrumb).also { result ->
if(scenario != null) result.updateScenario(scenario)
}
fun report(): String = resultReport(failure())
}
fun attempt(errorMessage: String = "", breadCrumb: String = "", f: ()->ReturnType): ReturnType {
try {
return f()
}
catch(contractException: ContractException) {
throw ContractException(errorMessage, breadCrumb, contractException)
}
catch(throwable: Throwable) {
throw ContractException("$errorMessage\nException thrown: $throwable", breadCrumb)
}
}
fun attempt(f: ()->ReturnType): ReturnType {
try {
return f()
}
catch(throwable: Throwable) {
throw ContractException("Exception thrown: ${throwable.localizedMessage}")
}
}
inline fun scenarioBreadCrumb(scenario: Scenario, f: ()->ReturnType): ReturnType {
try {
return f()
} catch(e: ContractException) {
throw e.copy(scenario = scenario)
}
}
fun resultOf(f: () -> Result): Result {
return try {
f()
} catch(e: Throwable) { Result.Failure(e.localizedMessage) }
}