Skip to content

API Reference

/

Errors

Errors

The Go SDK returns errors that you inspect with errors.As and errors.Is. This page lists each error type, the kinds of a server error and the helpers that match them, and the sentinel errors. For patterns that check and retry these errors, see Error handling.

Packages:

  • github.com/surrealdb/surrealdb.go/v2, which re-exports the error types of pkg/connection

  • github.com/surrealdb/surrealdb.go/v2/pkg/connection, which defines ServerError, RPCError and HealthError

  • github.com/surrealdb/surrealdb.go/v2/pkg/constants, which defines most sentinel errors

An error that the server reports for a request, such as a sign-in, a CRUD function or a query that does not parse. Use errors.As to read it from any error the SDK returns.

type ServerError struct {
	Code    int
	Message string
	Kind    string
	Details any
	Cause   *ServerError
}
FieldDescription
CodeThe JSON-RPC error code, such as -32000
MessageThe message of the error
KindThe kind of the error, one of the Kind constants
DetailsDetails for the kind, as { kind, details }, or nil
CauseThe next error in the chain, or nil

Methods:

  • .Error() returns the message, with the messages of the cause chain joined by ": "

  • .Unwrap() returns Cause, so that errors.Unwrap, errors.Is and errors.As walk the chain

Available as: surrealdb.ServerError, an alias of connection.ServerError

_, err := surrealdb.Create[Person](ctx, db, models.NewRecordID("person", "tobie"), person)

var se *surrealdb.ServerError
if errors.As(err, &se) {
	fmt.Println(se.Kind, se.Message)
}
Output when person:tobie exists
AlreadyExists Database record `person:tobie` already exists

The surrealdb package re-exports the known values of ServerError.Kind:

ConstantValue
KindValidation"Validation"
KindConfiguration"Configuration"
KindThrown"Thrown"
KindQuery"Query"
KindSerialization"Serialization"
KindNotAllowed"NotAllowed"
KindNotFound"NotFound"
KindAlreadyExists"AlreadyExists"
KindConnection"Connection"
KindInternal"Internal"

Errors documents the kinds and their details for every SDK.

Each helper reports whether an error is, or wraps, a *ServerError that matches its entry in the table below. It returns false for nil and for other errors.

HelperKind and detail
IsNotFound(err)NotFound
IsNotAllowed(err)NotAllowed
IsInvalidAuth(err)NotAllowed, Auth, InvalidAuth
IsTokenExpired(err)NotAllowed, Auth, TokenExpired
IsScriptingBlocked(err)NotAllowed, Scripting
IsParseError(err)Validation, Parse
IsTimedOut(err)Query, TimedOut
IsCancelled(err)Query, Cancelled
IsNotExecuted(err)Query, NotExecuted
IsTransactionConflict(err)Query, TransactionConflict, which is safe to retry
IsDeserialization(err)Serialization, Deserialization
IsLiveQueryNotSupported(err)Configuration, LiveQueryNotSupported
if surrealdb.IsNotFound(err) {
	fmt.Println("no such table")
}

The error of one failed statement of a query. It is the Error field of a QueryResult, and the Err field of the Done frame of a StreamFrame. The error that Query returns joins the QueryError of each failed statement.

type QueryError struct {
	Message string
}

Methods:

  • .Error() returns the message

  • .Is(target) returns true when target is a *QueryError, so errors.Is(err, &surrealdb.QueryError{}) reports whether err holds one

A QueryError holds the message only, so the Is helpers do not match it.

results, err := surrealdb.Query[any](ctx, db, "RETURN 1; THROW 'Not allowed';", nil)

if errors.Is(err, &surrealdb.QueryError{}) {
	for _, qr := range *results {
		if qr.Error != nil {
			fmt.Println(qr.Error.Message)
		}
	}
}
Output
An error occurred: Not allowed

The JSON-RPC error of a failed request, with Code and Message fields. It unwraps to a *ServerError, which has more information. Use errors.As with a *ServerError instead.

Available as: surrealdb.RPCError, an alias of connection.RPCError. It is deprecated.

The client returns this error when it connects to a server whose version is outside the range that the SDK supports. It does this only with WithVersionCheck(true).

type UnsupportedVersionError struct {
	Version string
	Minimum string
	Maximum string
}
FieldDescription
VersionThe version the server reported
MinimumThe oldest version supported, MinimumServerVersion
MaximumThe first version not supported, MaximumServerVersion

db.Health() returns this error when the server answers its health check with a status other than 2xx. The server does this, for example, when it cannot reach its datastore.

type HealthError struct {
	StatusCode int
	Status     string
	Body       string
}
FieldDescription
StatusCodeThe HTTP status code, such as 503
StatusThe HTTP status, such as 503 Service Unavailable
BodyThe start of the body, at most 4 KiB, with surrounding white space removed

Available as: surrealdb.HealthError, an alias of connection.HealthError

db.Import() returns this error when statements of the document fail. The server does not roll back the statements that succeed.

type ImportError struct {
	Failures []error
}

Failures holds the error of each failed statement, in order. Each error is an *RPCError that unwraps to a *ServerError.

Methods:

  • .Error() describes the first failure and the number of failures

  • .Unwrap() returns Failures, so errors.Is and errors.As look through each of them

Check these with errors.Is, because the SDK wraps some of them.

ErrorReturned when
ErrSessionsNotSupportedYou call Attach, Fork or Sessions on an HTTP connection
ErrTransactionsNotSupportedYou call Begin on an HTTP connection
ErrSessionClosedYou use a session after .Detach()
ErrTransactionClosedYou use a transaction after .Commit() or .Cancel()
ErrForkTokenExpiredYou call Fork after the access token of the session has expired
ErrForkUntrackedYou call Fork on a session that this client did not attach
ErrNeedsCBOR2The SDK tries to encode a value with no plain CBOR form, such as a models.Regex, for plain CBOR
ErrMethodNotAvailableA method is not available on the connection

ErrNoNamespaceOrDB is deprecated. The HTTP connection no longer needs a namespace and database for every request, and does not return it.

ErrorReturned when
ErrClientClosedYou use the client after .Close(), or after it gave up reconnecting
ErrLiveQueryEndedThe client ended a live query, instead of restarting it, when it reconnected
ErrStreamProtocolThe frames of a streamed query break the streaming protocol
ErrorReturned when
ErrConnectionClosedThe client lost the connection while a request waited for its answer

A request that times out returns an error that wraps context.DeadlineExceeded.

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")
}
  • Error handling for patterns that check errors, and for retry guidance

  • Types reference for QueryResult and StreamFrame

  • DB reference for the functions that return these errors

  • Errors for the error kinds that every SDK shares

Was this page helpful?

Last updated