Custom errors
suggest changeIn Kotlin, error handling spans two complementary paradigms:
- Exception-based errors: Extending
ExceptionorRuntimeExceptionfor unexpected, catastrophic, or operational failures. - Typed domain errors: Using
sealed classorsealed interfacehierarchies alongsidekotlin.Resultfor expected, recoverable business failures (railway-oriented programming).
Unlike Java, Kotlin does not have checked exceptions—all exceptions are unchecked at compile-time.
Defining Custom Exception Classes
To create custom exceptions, extend Exception (or RuntimeException) and delegate to the superclass constructors:
// Base application exception
open class AppException(
message: String,
cause: Throwable? = null
) : RuntimeException(message, cause)
// Specific domain exception with structured metadata
class UserNotFoundException(
val userId: String
) : AppException("User with ID '$userId' was not found.")
class InsufficientFundsException(
val accountId: String,
val required: Double,
val available: Double
) : AppException(
"Account '$accountId' has insufficient funds: required $$required, but only $$available available."
)
Throwing and Catching
fun withdraw(accountId: String, amount: Double, balance: Double) {
if (amount > balance) {
throw InsufficientFundsException(accountId, amount, balance)
}
println("Withdrew $$amount from account $accountId")
}
fun main() {
try {
withdraw("acc_881", 250.0, 100.0)
} catch (e: InsufficientFundsException) {
println("Transaction rejected: ${e.message}")
println("Account: ${e.accountId}, Shortfall: $${e.required - e.available}")
} catch (e: AppException) {
println("Application error: ${e.message}")
}
}
Typed Domain Errors with Sealed Interfaces
For predictable domain outcomes (such as authentication failures, payment declines, or validation errors), throwing exceptions introduces invisible control flow jumps and performance overhead.
Using sealed interface guarantees type-safe, exhaustive error handling at compile time:
sealed interface PaymentError {
data class CardExpired(val expirationDate: String) : PaymentError
data class InsufficientBalance(val available: Long, val needed: Long) : PaymentError
data class FraudAlert(val reason: String) : PaymentError
data object NetworkTimeout : PaymentError
}
data class PaymentReceipt(val transactionId: String, val amountCents: Long)
// Function returns Either Success OR Error
sealed interface PaymentResult {
data class Success(val receipt: PaymentReceipt) : PaymentResult
data class Failure(val error: PaymentError) : PaymentResult
}
fun processPayment(amountCents: Long, cardBalanceCents: Long): PaymentResult {
return when {
amountCents <= 0 -> PaymentResult.Failure(PaymentError.FraudAlert("Invalid transaction amount"))
cardBalanceCents < amountCents -> PaymentResult.Failure(
PaymentError.InsufficientBalance(available = cardBalanceCents, needed = amountCents)
)
else -> PaymentResult.Success(PaymentReceipt("tx_9981", amountCents))
}
}
fun main() {
val result = processPayment(amountCents = 5000, cardBalanceCents = 2000)
// Exhaustive compile-time checking with `when`
when (result) {
is PaymentResult.Success -> println("Payment succeeded: ${result.receipt.transactionId}")
is PaymentResult.Failure -> when (val err = result.error) {
is PaymentError.CardExpired -> println("Card expired on ${err.expirationDate}")
is PaymentError.InsufficientBalance -> println("Insufficient balance: need ${err.needed}, have ${err.available}")
is PaymentError.FraudAlert -> println("Transaction blocked: ${err.reason}")
is PaymentError.NetworkTimeout -> println("Gateway timed out. Please retry.")
}
}
}
Handling Errors with kotlin.Result
The Kotlin standard library includes Result<T> and the runCatching inline function:
fun parseConfigPort(portStr: String): Result<Int> {
return runCatching {
val port = portStr.toInt()
require(port in 1..65535) { "Port must be between 1 and 65535" }
port
}
}
fun main() {
val result = parseConfigPort("8080")
.onSuccess { port -> println("Binding to port $port") }
.onFailure { error -> println("Invalid port: ${error.message}") }
// Fallback to default port on error
val activePort = parseConfigPort("invalid").getOrElse { 3000 }
println("Active port: $activePort") // 3000
}
Mapping Custom Errors in Web APIs (e.g., Ktor / Spring)
In HTTP services, custom domain errors can be mapped to standard HTTP response codes via a centralized exception handler:
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.*
import io.ktor.server.plugins.statuspages.*
import io.ktor.server.response.*
fun Application.configureErrorHandling() {
install(StatusPages) {
exception<UserNotFoundException> { call, cause ->
call.respond(
HttpStatusCode.NotFound,
mapOf("error" to "USER_NOT_FOUND", "message" to cause.message)
)
}
exception<InsufficientFundsException> { call, cause ->
call.respond(
HttpStatusCode.PaymentRequired,
mapOf(
"error" to "INSUFFICIENT_FUNDS",
"required" to cause.required,
"available" to cause.available
)
)
}
exception<Throwable> { call, cause ->
call.respond(
HttpStatusCode.InternalServerError,
mapOf("error" to "INTERNAL_SERVER_ERROR", "message" to "An unexpected error occurred.")
)
}
}
}
Best Practices
- Use typed sealed classes for expected business branches: Validation errors, expired tokens, and insufficient funds are valid business logic scenarios—represent them in return types rather than throwing exceptions.
- Reserve exceptions for exceptional failures: Use exceptions for catastrophic errors such as database connection loss, disk failures, or unrecoverable bugs.
- Include structured diagnostic context: Store entity IDs, timestamps, or constraint values in dedicated properties on custom error classes rather than burying them in formatted text messages.
- Preserve the root cause: When translating lower-level exceptions into domain exceptions, always forward the original
causeparameter to preserve stack traces.