• Start

Languages

/

Kotlin

/

Concepts

Error handling

Handle exceptions and feature-support errors raised by the SurrealDB Kotlin SDK.

Networked operations on the SDK throw a SurrealException on failure, or you can use the Result variants to handle failures functionally without exceptions.

All SDK exceptions extend the sealed base SurrealException.

ExceptionRaised when
SurrealTransportExceptionThe connection fails or drops
SurrealProtocolExceptionA malformed or unexpected protocol message is received
SurrealRpcExceptionThe server returns an RPC error (carries code and data)
SurrealAuthenticationExceptionAuthentication fails (a subclass of SurrealRpcException)
SurrealFeatureNotSupportedExceptionA feature is unavailable on the current transport

Because SurrealException is a sealed class, you can exhaustively branch on it with when.

import com.surrealdb.kotlin.error.SurrealAuthenticationException
import com.surrealdb.kotlin.error.SurrealException
import com.surrealdb.kotlin.error.SurrealRpcException
import com.surrealdb.kotlin.error.SurrealTransportException

try {
client.signin(buildJsonObject {
put("user", "root")
put("pass", "wrong")
})
} catch (e: SurrealAuthenticationException) {
println("bad credentials: ${e.message}")
} catch (e: SurrealRpcException) {
println("server error ${e.code}: ${e.message}")
} catch (e: SurrealTransportException) {
println("connection problem: ${e.message}")
} catch (e: SurrealException) {
println("unexpected: ${e.message}")
}

Calling a feature that the current transport does not support — for example a live query over HTTP — throws SurrealFeatureNotSupportedException. Guard against this with .supports().

import com.surrealdb.kotlin.SurrealFeature

if (client.supports(SurrealFeature.LiveQueries)) {
val subscription = client.live("person")
}

Each networked method has a ...Result companion that wraps the outcome in a Result instead of throwing.

client.queryResult("SELECT * FROM person")
.onSuccess { println("got $it") }
.onFailure { println("failed: ${it.message}") }

Was this page helpful?