All Downloads are FREE. Search and download functionalities are using the official Maven repository.

in.specmatic.core.pattern.ContractException.kt Maven / Gradle / Ivy

Go to download

Turn your contracts into executable specifications. Contract Driven Development - Collaboratively Design & Independently Deploy MicroServices & MicroFrontends. Deprecation Notice for group ID "in.specmatic" ****************************************************************************************************** Updates for "specmatic-core" will no longer be available under the deprecated group ID "in.specmatic". Please update your dependencies to use the new group ID "io.specmatic". ******************************************************************************************************

There is a newer version: 1.3.39
Show newest version
package `in`.specmatic.core.pattern

import `in`.specmatic.core.FailureReport
import `in`.specmatic.core.Result
import `in`.specmatic.core.ScenarioDetailsForResult

fun isCycle(throwable: Throwable?): Boolean = when(throwable) {
    is ContractException -> throwable.isCycle
    else -> false
}

data class ContractException(
    val errorMessage: String = "",
    val breadCrumb: String = "",
    val exceptionCause: Throwable? = null,
    val scenario: ScenarioDetailsForResult? = null,
    val isCycle: Boolean = isCycle(exceptionCause)
) : Exception(errorMessage, exceptionCause) {
    constructor(failureReport: FailureReport): this(failureReport.errorMessage(), failureReport.breadCrumbs())

    fun failure(): Result.Failure =
        Result.Failure(errorMessage,
            if (exceptionCause is ContractException) exceptionCause.failure() else null,
            breadCrumb
        ).also { result ->
            if(scenario != null) result.updateScenario(scenario)
        }

    fun report(): String = failure().toReport().toText()
}

fun  attempt(errorMessage: String = "", breadCrumb: String = "", f: ()->ReturnType): ReturnType {
    try {
        return f()
    }
    catch(contractException: ContractException) {
        throw ContractException(errorMessage, breadCrumb, contractException, contractException.scenario)
    }
    catch(throwable: Throwable) {
        throw ContractException("$errorMessage\nError: $throwable", breadCrumb, throwable)
    }
}

fun  attempt(f: ()->ReturnType): ReturnType {
    try {
        return f()
    }
    catch(throwable: Throwable) {
        throw ContractException("Error: ${throwable.localizedMessage}", exceptionCause = throwable)
    }
}

inline fun  scenarioBreadCrumb(scenario: ScenarioDetailsForResult, 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) }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy