Handle errors in the SurrealDB Python SDK
mainAll SDK errors derive from SurrealError. Errors are categorized into two main branches based on whether the request reached the server and whether the server rejected it:
ServerError: The server received and processed the request but rejected it (e.g., syntax errors, permission issues). These are generally not retryable without changes.ServerErrorincludes specific subclasses likeNotFoundErrorthat mirror SurrealDB's structured error format, allowing you to match onkindanddetails.TransportError: The request failed to produce a structured response (e.g., network failure, timeout). These may be retryable.
Common TransportError subclasses include:
ConnectionUnavailableError: Host unreachable or socket closed.TransportTimeoutError: Request timed out.HttpStatusError: A non-2xx HTTP response (contains.status,.body, and.url).
Invalid Python inputs (like wrong types) will raise standard ValueError or TypeError before reaching the server.
from surrealdb import Surreal
from surrealdb.errors import NotFoundError, ServerError, SurrealError, TransportError
with Surreal("ws://localhost:8000/rpc") as db:
db.signin({"username": "root", "password": "root"})
db.use("ns", "db")
try:
db.query("SELECT * FROM nonexistent:1").execute()
except NotFoundError as error:
print(error.kind, error.table_name) # NotFound nonexistent
except ServerError as error:
print(error.kind, error.details)
except TransportError as error:
print("could not reach the server:", error)