Error handling in SurrealQL allows you to stop execution and return a meaningful error when something goes wrong. This is most commonly done using the THROW statement.
Throwing an error
You can use THROW to immediately stop a query and return an error to the client:
When executed, the query is aborted and the error is returned.
THROW is often used to validate input or guard business logic:
THROW is especially useful inside manual transactions.
Returning custom error messages
The value passed to THROW is returned to the client.
You can also include dynamic data:
Or even structured data.
Avoiding errors
Type safety and strict definitions can be used to avoid throwing errors based on custom logic. For example, the ASSERT clause in a DEFINE FIELD statement can be used to ensure that a statement will fail if the string for the email field provided is not a valid email.
Working with a schema in this way allows throwing errors to be taken care of by the definitions themselves as opposed to writing custom logic.
SDK error handling
SurrealDB uses a single public API error type that is shared by SDKs. As the repo states, the error type is:
Designed to be returned from public APIs (including over the wire). It is wire-friendly and non-lossy: serialization preserves
kind,message, and optionaldetails. Use this type whenever an error crosses an API boundary (e.g. server response, SDK method return).The
detailsfield is flattened into the serialized object, so the wire format containskind(string) and optionallydetails(object) at the same level ascodeandmessage. The optionalcausefield allows error chaining so that SDKs can receive and display full error chains.
This error will then be handled in a different manner depending on the programming language the SDK is written for.