Skip to content

Concepts

Error handling

The Go SDK returns ordinary Go errors, which you inspect with errors.As and errors.Is. A failure belongs to one of three groups:

  • An error that the server reports for a request

  • The error of one statement in a query

  • A failure in the client or the network

This page shows how to tell the groups apart and how to match on the kind of a server error. It also shows which errors are safe to retry.

The Errors page documents the error kinds, wire codes and structured shape behind these errors once, for every SDK and protocol.

Error

Description

ServerError

An error from the server, with a kind, details and a cause chain

QueryError

The error of one failed statement in a query

IsNotFound

,

IsNotAllowed

and others

Report whether an error is a server error of a given kind

UnsupportedVersionError

The server version is outside the range the SDK supports

HealthError

The server answered the health check with an unsuccessful status

ImportError

Statements of an imported document failed

Sentinel errors

Fixed errors, such as

ErrSessionClosed

and

ErrClientClosed

The SDK reports each kind of failure in its own way:

FailureHow it surfaces
The server refuses a request, such as a sign-in, a CRUD function, or a whole query that does not parseThe returned error is an *RPCError that unwraps to a *ServerError
One statement of a query failsThe statement's QueryResult.Error is a *QueryError, and the returned error joins them
The connection is lost, or a request times outThe returned error wraps connection.ErrConnectionClosed or context.DeadlineExceeded
The result does not fit the type parameterThe returned error starts with Send: error unmarshaling result
A call is not possible on this client, such as a session over HTTPA sentinel error, such as constants.ErrSessionsNotSupported

Use errors.As to read the ServerError of a failed request. It holds the Kind of the error, a Message, kind-specific Details, and an optional Cause:

_, err := surrealdb.Create[Person](ctx, db, models.NewRecordID("person", "tobie"), person)
if err != nil {
	var se *surrealdb.ServerError
	if errors.As(err, &se) {
		fmt.Println(se.Kind, se.Details)
	}
}
Output when person:tobie exists
AlreadyExists map[details:map[id:person:tobie] kind:Record]

Cause is the next error in the chain, and is itself a *ServerError. .Error() joins the messages of the chain with ": ". To go through the chain one error at a time, use errors.Unwrap.

Compare Kind with the Kind constants, such as surrealdb.KindAlreadyExists. You can also use one of the Is helpers, which find the *ServerError for you:

_, err := surrealdb.Select[[]Person](ctx, db, models.Table("person"))
switch {
case surrealdb.IsNotFound(err):
	fmt.Println("the table does not exist yet")
case surrealdb.IsNotAllowed(err):
	fmt.Println("not allowed to read the table")
case err != nil:
	log.Fatal(err)
}
HelperMatches
IsNotFoundA table, record, namespace, database, session or transaction that does not exist
IsNotAllowedAny NotAllowed error, such as a permission or an authentication failure
IsInvalidAuthCredentials that the server refused
IsTokenExpiredAn access token that has expired
IsScriptingBlockedA script that the server's capabilities do not allow
IsParseErrorA query that does not parse
IsTimedOutA query that passed its TIMEOUT
IsCancelledA query that was cancelled
IsNotExecutedA statement that never ran, usually because an earlier statement in its transaction failed
IsTransactionConflictA transaction that conflicted with another one, which is safe to retry
IsDeserializationA value that the server could not decode
IsLiveQueryNotSupportedA live query on a connection or server that cannot run one

Match on the kind rather than the message. The text of a message can change between SurrealDB versions. Also, from version 2 of the SDK, the CRUD functions run as queries, which changed some of their messages.

Query returns a result for each statement, and a statement can fail while the others succeed. The QueryResult.Error of the failed statement is then a *QueryError:

results, err := surrealdb.Query[any](ctx, db,
	"CREATE person:tobie; CREATE person:tobie;",
	nil,
)

for i, qr := range *results {
	if qr.Error != nil {
		fmt.Printf("statement %d failed: %s\n", i, qr.Error.Message)
	}
}
Output
statement 1 failed: Database record `person:tobie` already exists

The returned err joins the *QueryError of every failed statement. errors.Is(err, &surrealdb.QueryError{}) reports whether err holds one. Use it to tell a statement failure apart from a transport or decoding failure:

if errors.Is(err, &surrealdb.QueryError{}) {
	fmt.Println("one or more statements failed")
}

A QueryError holds the message only, so the Is helpers do not match it. To get the kind of a failure, run the operation with a CRUD function, which returns a *ServerError. You can also check the message of the statement.

Connecting can fail before the client sends any request:

ErrorCause
invalid connection urlThe URL has no scheme, or a scheme other than ws, wss, http or https
embedded database not enabledThe URL uses mem://, memory or surrealkv://. See Embedding.
*UnsupportedVersionErrorWith WithVersionCheck(true), the server version is outside the supported range
A network error, such as connection refusedThe server cannot be reached

.Health() returns a *HealthError when the server answers its health check with a status other than 2xx:

var he *surrealdb.HealthError
if err := db.Health(ctx); errors.As(err, &he) {
	log.Printf("server unhealthy: %d %s", he.StatusCode, he.Body)
}

DB.Import keeps every statement of a document that succeeds, even when other statements fail. When some fail, it returns an *ImportError, which lists the error of each failed statement:

err := db.Import(ctx, file)

var ie *surrealdb.ImportError
if errors.As(err, &ie) {
	for _, failure := range ie.Failures {
		log.Println(failure)
	}
}

Each failure unwraps to a *ServerError, so the Is helpers work on it. See Import and export.

The SDK returns fixed errors for conditions that do not come from the server. Check them with errors.Is:

import "github.com/surrealdb/surrealdb.go/v2/pkg/constants"

session, err := db.Attach(ctx)
if errors.Is(err, constants.ErrSessionsNotSupported) {
	log.Fatal("sessions need a WebSocket connection")
}
ErrorReturned when
constants.ErrSessionsNotSupportedAttach, Fork or Sessions is called on an HTTP connection
constants.ErrTransactionsNotSupportedBegin is called on an HTTP connection
constants.ErrSessionClosedA session is used after .Detach()
constants.ErrTransactionClosedA transaction is used after .Commit() or .Cancel()
constants.ErrForkTokenExpiredFork is called after the session's access token has expired
constants.ErrForkUntrackedFork is called on a session that this client did not attach
constants.ErrNeedsCBOR2A value with no plain CBOR form, such as a models.Regex, is sent to a server before SurrealDB 4.0
surrealdb.ErrClientClosedThe client is used after .Close()
surrealdb.ErrLiveQueryEndedA live query was ended, instead of restarted, when the client reconnected
surrealdb.ErrStreamProtocolThe frames of a streamed query break the streaming protocol
connection.ErrConnectionClosedThe connection was lost while a request waited for its answer

The SDK wraps the errors in constants in some cases, so use errors.Is rather than ==.

Retry only a request that failed for a reason that does not depend on the request itself:

ErrorRetryReason
IsTransactionConflictYesAnother transaction changed the same data. Running it again usually succeeds.
context.DeadlineExceededYes, with careThe request timed out, and may or may not have run. Retry only work that is safe to repeat.
connection.ErrConnectionClosedYes, with careThe connection was lost while the request was in flight, so it may or may not have run. A reconnecting client sends later requests on the new connection.
QueryErrorNoThe statement itself failed, for example because of its data or a THROW.
Another ServerError kind, such as NotAllowed or AlreadyExistsNoThe request is refused, and sending it again gives the same answer.
A decoding errorNoThe type parameter does not match the result.

SurrealDB 3.x reports some errors with less precise kinds than 4.0. For example, a value that does not match the type of a field gives an Internal error with code -32000 on 3.x. On 4.0, it gives a Validation error with code -32600. Code that has to work with both versions should not depend on Kind or Details having the 4.0 values.

Was this page helpful?

Last updated