Custom errors

suggest change

In Kotlin, error handling spans two complementary paradigms:

  1. Exception-based errors: Extending Exception or RuntimeException for unexpected, catastrophic, or operational failures.
  2. Typed domain errors: Using sealed class or sealed interface hierarchies alongside kotlin.Result for 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents