Skip to content

Instantly share code, notes, and snippets.

@corneil
Created August 28, 2019 20:49
Show Gist options
  • Save corneil/bf38eaf043ccd75e1de5861b2e1bcb1f to your computer and use it in GitHub Desktop.
Save corneil/bf38eaf043ccd75e1de5861b2e1bcb1f to your computer and use it in GitHub Desktop.
precondition extension functions with @ResponseStatus on Exception for Spring MVC.
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ResponseStatus
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
@ResponseStatus(HttpStatus.PRECONDITION_FAILED)
class PreconditionException(message: String) : Exception(message)
@ExperimentalContracts
@Throws(EntityNotFoundException::class)
inline fun precondition(check: Boolean, messageExpr: () -> String) {
contract { returns() implies check }
if (!check) throw PreconditionException(messageExpr.invoke())
}
@ExperimentalContracts
@Throws(EntityNotFoundException::class)
inline fun precondition(check: Boolean, exception: String) {
contract { returns() implies check }
if (!check) throw PreconditionException(exception)
}
@corneil
Copy link
Author

corneil commented Aug 28, 2019

contract ensures the the following:

val someThing: String? = someFunction()
precondition(someThing != null, "someThing is required")
funcWithNonNullArguments(someThing)

Can be used without adding !! to funcWithNonNullArguments(someThing)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment