Skip to main content

Handling Errors

VulcanSQL SQL Templates, like most programming languages, support error handling. To define an exception in your SQL templates, use the {% error "ERROR_CODE" %} syntax. When the template encounters an error during execution, VulcanSQL halts further execution and sends an error code to the client, rather than returning query results.

Consider the following example, where a check is performed before executing the main query:

{% req user %}
SELECT COUNT(*) AS count FROM customers WHERE name = {{ }}
{% endreq %}

{% if user.value()[0].count == 0 %}
{% error "CUSTOMER_NOT_FOUND" %}
{% endif %}

SELECT * FROM customers
WHERE name = {{ }}

In this case, if clients send API requests with an invalid name, they will receive a 400 error along with the error code CUSTOMER_NOT_FOUND, instead of an empty array. This approach allows you to gracefully handle errors and provide meaningful feedback to the client.