Error handling

This guide covers error handling for applications that work directly with the Fauna Core HTTP API.

You can use the Core HTTP API to:

The Fauna client drivers, Fauna Dashboard, and Fauna CLI use the Core HTTP API internally.

Error responses

Error responses from Core HTTP API endpoints contain an error object with the following properties:

  • code: A Fauna-specific error code.

  • message: A human-readable error description.

The error object can optionally include these properties:

Errors response may include additional properties, such as a summary that indicates the location of the error, if applicable:

{
  "error": {
    "code": "invalid_query",
    "message": "invalid query: the query failed 1 validation check"
  },
  "summary": "error: the function `len` does not exist on string\n0: *query*:1\n |\n1 | 'foo'.len()\n  |       ^^^\n  |\n",
  ...
}

You can use query tags to track Query endpoint requests that produce errors in Fauna Logs .

Error codes

Fauna error codes are part of the API contract and are safe to write programmatic logic against.

You should first handle errors based on their error code.

The table contains a non-exhaustive list of common error codes.

abort

conflict

constraint_failure

contended_transaction

disabled_feature

divide_by_zero

document_deleted

document_id_exists

document_not_found

eval_error

forbidden

index_out_of_bounds

internal_error

internal_failure

invalid_argument

invalid_bounds

invalid_computed_field_access

invalid_cursor

invalid_date

invalid_document_id

invalid_effect

invalid_function_invocation

invalid_id

invalid_index_invocation

invalid_null_access

invalid_receiver

invalid_regex

invalid_request

invalid_schema

invalid_secret

invalid_time

invalid_timestamp_field_access

invalid_type

invalid_unit

invalid_write

limit_exceeded

method_not_allowed

not_found

null_value

permission_denied

request_size_exceeded

stack_overflow

time_out

tmp_write_failed

type_mismatch

unauthorized

unbound_variable

value_too_large

HTTP status codes

If an error contains an unrecognized code, you can address it according to the response’s HTTP status code. Most 4xx and 5xx errors have an associated Fauna error code.

Range Description

200-299

Successful request.

HTTP status code Description

200

Request succeeded.

400-499

Client error

HTTP status code Description Related error code

400

Bad request. The request does not conform to API specifications.

invalid_request

401

The request’s authentication secret is invalid or missing.

unauthorized

403

The request’s authentication secret does not have the required privileges.

forbidden

404

Resource not found.

not_found

405

The request’s HTTP method is not allowed.

method_not_allowed

409

The request failed due to a resource conflict.

conflict

410

A requested feature is disabled for the account.

forbidden

413

The request’s payload exceeded the maximum payload size.

request_size_exceeded

429

The request exceeded throughput limits. You can safely retry the request. See Throttling errors and rate limits.

limit_exceeded

440

Client timeout exceeded. Unlike a 503 HTTP status code, this timeout isn’t related to Fauna service availability.

time_out

500-599

Server error

HTTP status code Description Related error code

500

Unexpected error from the Fauna service.

internal_error

503

Unexpected timeout due to Fauna service availability.

time_out

540

The Fauna service failed unexpectedly.

internal_error

Error classification

You can create classes for Fauna errors based on their error code:

Error class Error codes Cause

Abort

abort

An abort() call caused the query to abort. See Abort errors.

Authentication

forbidden
unauthorized

One of the following:

  • The request’s authentication secret is invalid or missing.

  • The request’s authentication secret does not have the required privileges.

  • A requested feature is disabled for the account.

Constraint failure

constraint_failure

The request’s query failed a check or unique constraint. See Constraint failure errors.

The response’s error object includes a constraint_failures array. The array contains information about the constraints that triggered the error.

Contended transaction

contended_transaction

The request failed due to transaction contention.

Invalid request

invalid_request

Bad request. The request does not conform to API specifications.

Query check

invalid_query

Before execution, one or more query validation checks failed.

Query runtime

Unhandled error codes with a 4xx HTTP status code.

The request’s FQL query is invalid and failed during evaluation.

Query timeout

time_out

The request processing time exceeded the defined timeout.

Throttling

limit_exceeded

The request exceeded plan throughput limits. You can safely retry the request. See Throttling errors and rate limits.

Service internal

internal_error

The Fauna service failed unexpectedly.

For examples of how Fauna’s client drivers classify and handle errors, see:

Abort errors

The FQL abort() method lets you intentionally return an error in an FQL query or UDF. abort() requires a user-defined return value:

For example, in a UDF:

function checkout(orderId, status, payment) {
  ...
  // Abort the query if its calls `checkout()` with a
  // `status` other than `processing`.
  if (status != "processing") {
    // `Abort()` accepts a user-defined error message.
    abort("Cannot call checkout with status other than processing.")
  }
}

Abort errors use the abort error code and include the return value in the error.abort property:

{
  "error": {
      "code": "abort",
      "message": "Query aborted.",
      "abort": "\"Cannot call checkout with status other than processing.\""
  },
  ...
}

The return value is encoded to JSON using the data format specified in the Query HTTP API request’s X-Format header.

Fauna’s client drivers include classes for abort errors:

Constraint failure errors

Queries that fail a check or unique constraint return an error.

Constraint errors use the constraint_failure error code and include an array of constraint failures in the error object’s constraint_failures array:

{
  "error": {
    "code": "constraint_failure",
    "message": "Failed to create document in collection `Product`.",
    "constraint_failures": [
      {
        "paths": [],
        "message": "Document failed check constraint `stockIsValid`"
      }
    ]
  },
  ...
}

Objects in the constraint_failures array can also include an optional name property that contains the name of the failed constraint.

Fauna’s client drivers include classes for constraint errors:

Throttling errors and rate limits

Requests that exceed plan throughput limits return an error with a:

  • limit_exceeded error code

  • 429 HTTP status code.

  • X-Rate-Limited-Ops HTTP header. The header value indicates the operation types that triggered the error, such as compute, `read, or write.

  • stats.rate_limits_hit property in the error response. The property’s value indicates the operation types that triggered the error.

{
  "error": {
    "code": "limit_exceeded",
    "message": "Rate limit exceeded",
  },
  ...
  "stats": {
    ...
    "rate_limits_hit": [
      "compute",
      "read",
      "write"
    ]
  },
  ...
}

Retrying throttling errors

You can safely retry limit_exceeded errors. We recommend using an exponential backoff.

Fauna’s client drivers include client configuration settings to automatically retry limit_exceeded errors with exponential backoff. See:

Error handling example

The following example shows how to handle errors based on error codes:

const FAUNA_SECRET = '<FAUNA_SECRET>';

async function fetchFaunaData(query, args = {}) {
  try {
    const response = await fetch('https://db.fauna.com/query/1', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${FAUNA_SECRET}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        query: query,
        arguments: args
      })
    });

    const data = await response.json();

    // Check if an error object is present in the response
    if (data.error) {
      handleFaunaError(data.error, response.status);
    } else {
      console.log('Query successful:', data);
      return data;
    }
  } catch (error) {
    console.error('Request failed:', error);
  }
}

// Error handling based on Fauna error codes
/**
  This function contains a description of each
  Fauna error codes and how to handle them.
*/
function handleFaunaError(error, statusCode) {
  switch (error.code) {

    /**
    * An error returned by calling the FQL `abort()` function.
    */
    case 'abort':
      console.error('Transaction aborted:', error.message);
      break;

    /**
    * A runtime error due to failing schema constraints.
    */
    case 'constraint_failure':
      console.error('Constraint failure:', error.message);
      break;

    /**
    * Feature disabled error.
     */
    case 'disabled_feature':
      console.error('Feature disabled:', error.message);
      break;

    /**
    * An error due to a deleted document.
    */
    case 'document_deleted':
      console.error('Document deleted:', error.message);
      break;

    /**
     * An error due to a missing document.
     */
    case 'document_not_found':
      console.error('Document not found:', error.message);
      break;

    /**
    * A type of AuthorizationError that indicates the user does not have
    * privileges to perform requested operations.
    */
    case 'forbidden':
      console.error('Forbidden:', error.message);
      break;

    /**
    * A type of ServiceInternalError indicates Fauna failed unexpectedly.
     */
    case 'internal_error':
      console.error('Internal error:', error.message);
      break;

    /**
    * An error due to an invalid argument or query.
    */
    case 'invalid_argument':
    case 'invalid_computed_field_access':
    case 'invalid_date':
    case 'invalid_effect':
    case 'invalid_id':
    case 'invalid_null_access':
    case 'invalid_regex':
    case 'invalid_schema':
    case 'invalid_time':
    case 'invalid_type':
    case 'invalid_write':
      console.error('Invalid Error:', error.message);
      break;

    /**
    * An error due to invalid method invocation.
    */
    case 'method_not_allowed':
      console.error('Method not allowed:', error.message);
      break;

    /**
    * An error due to a null value.
    */
    case 'null_value':
      console.error('Null value:', error.message);
      break;

    /**
    * Request exceeds the maximum HTTP request payload.
    */
    case 'request_size_exceeded':
      console.error('Request size exceeded:', error.message);
      break;

    /**
    * Type of Authentication Error indicates invalid credentials were
    * used.
    */
    case 'unauthorized':
      console.error('Unauthorized:', error.message);
      break;

    /**
    * Indicates a throughput limit was exceeded
    * and thus the request could not be served.
    */
    case 'limit_exceeded':
      console.error('Limit exceeded:', error.message);
      break;

    /**
    * A failure due to the query timeout being exceeded.
    *
    * This error can have one of two sources:
    *     1. Fauna is behaving expectedly, but the query timeout provided was too
    *        aggressive and lower than the query's expected processing time.
    *     2. Fauna was not available to service the request before the timeout was
    *        reached.
    *
    * In either case, consider increasing the `query_timeout_ms` configuration for
    * your client.
    */
    case 'time_out':
      console.error('Time out:', error.message);
      break;

    /**
    * An error due to a contended transaction.
    */
    case 'contended_transaction':
      console.error('Contended transaction:', error.message);
      break;
  }

  // Log the status code for reference.
  console.error('Status code:', statusCode);
  // You can also log a summary if available.
  if (error.summary) {
    console.error('Error summary:', error.summary);
  }
}

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!