# GraphQL error handling

Audience: Developer

GraphQL Error Handling

## Overview

This document describes the error formats and best practices for handling various error conditions.

## Error structure

GraphQL errors are returned in a standardized format as part of the response:

```json
{
  "data": { ... },  // Might be null or partial if there were errors
  "errors": [
    {
      "message": "A human-readable error message",
      "locations": [{ "line": 2, "column": 3 }],
      "path": ["query", "fieldWithError"],
      "extensions": {
        "code": "ERROR_CODE",
        "httpStatus": 400
      }
    }
  ]
}
```

`extensions` is not present on every error. Pyck adds `extensions.code` only to the errors listed under Error Codes below. Most errors carry just `message` and `path`. There is no `details` field.

## Error codes

Pyck sets `extensions.code` on a small set of errors:

- `INVALID_PAGINATION`: `first` or `last` on a connection was less than zero.
- Idempotency errors, returned when a mutation carries an `Idempotency-Key` header. They also carry `extensions.httpStatus` with the intended HTTP status, because the response itself is sent with HTTP status 200:
  - `INVALID_IDEMPOTENCY_KEY` (400): the key is longer than 255 bytes or is not valid UTF-8.
  - `MISSING_OPERATION_NAME` (400): the request has a key but no `operationName`.
  - `MULTI_FIELD_MUTATION` (400): the request has a key and more than one top-level mutation field.
  - `UNAUTHENTICATED` (400): the request has a key but no authenticated user, or it does not resolve to exactly one tenant.
  - `INVALID_VARIABLES` (400) and `INVALID_IDEMPOTENCY_REQUEST` (400): the request could not be checksummed.
  - `OPERATION_MISMATCH` (422): the key was already used with a different operation or variables.
  - `IDEMPOTENCY_IN_FLIGHT` (409): a request with the same key is still running.
  - `RESPONSE_TOO_LARGE` (413): the response is too large to cache, so the mutation was rolled back.
  - `IDEMPOTENCY_STORE_ERROR`, `IDEMPOTENCY_RACE_GHOST`, `IDEMPOTENCY_CACHE_CORRUPT` and `IDEMPOTENCY_UNKNOWN_STATUS` (500): a server-side fault in the idempotency store.

Other errors, such as a failed validation or a missing record, have no Pyck-specific code. Branch on the `message` text and the HTTP status, not on a code.

## Error handling strategies

### Authentication errors

An expired or invalid token is rejected over HTTP before GraphQL runs: status 401 with the body `{"error": "Unauthorized"}`. When you receive a 401:

- Check that you're including a valid token in the Authorization header
- Verify that the token hasn't expired
- Request a new token if needed

### Permission errors

When you are denied access to a resource:

- Verify that the user has the necessary permissions
- Check if the user is trying to access resources outside their tenant
- Consider requesting additional permissions if needed

### Disabled tenant access errors

Requests that name a disabled tenant are rejected over HTTP before GraphQL runs: status 403 with a body `{"error": "tenant is disabled ..."}`, or 401 when it is your own (home) tenant. See [Disabled tenant behavior](https://docs.pyck.cloud/dev/developers/headers.md#disabled-tenant-behavior).

### Input validation errors

When a request contains invalid input values:

- Read the `message`, which names the problem
- Validate input data before sending it to the API
- Display helpful error messages to guide users

### Constraint violation errors

When a write breaks a database integrity constraint, the error `message` is a fixed text followed by the PostgreSQL SQLSTATE in parentheses. The message never names the table or the constraint. These errors have no `extensions.code`, so branch on the message text or the SQLSTATE.

| Message | Cause |
| --- | --- |
| `duplicate key: record already exists (SQLSTATE 23505)` | A unique value, such as an item `sku`, is already in use. |
| `referenced record does not exist (SQLSTATE 23503)` | An insert or update points at a record that does not exist. |
| `record is still referenced by other records (SQLSTATE 23503)` | An update or delete of a record that other records still point at. |
| `request violates a data constraint (SQLSTATE <code>)` | Any other integrity violation. `<code>` is its SQLSTATE, for example `23502` for a missing required value. |

What a client can rely on:

- Clients match on the wording. The unique violation text keeps both `duplicate key` and `23505`: the Go workflow SDK retries a lost registration race on either one, and workers treat `duplicate key` on a create as "it already exists".
- When a violation only surfaces at commit, the error carries the `path` of the first top-level field of the operation.
- The server does not retry the transaction for these errors, unlike a serialization failure or a deadlock.
- The table and constraint names are logged on the server only.

## Error handling example

This example handles errors in a client application:

```javascript
async function executeGraphQLQuery(query, variables) {
  try {
    const response = await fetch('https://eu.pyck.cloud/graphql', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({ query, variables })
    });

    const result = await response.json();
    
    if (result.errors) {
      // Handle different error types
      result.errors.forEach(error => {
        const code = error.extensions?.code;
        
        switch (code) {
          case 'OPERATION_MISMATCH':
            // The Idempotency-Key was reused for a different operation
            generateNewIdempotencyKey();
            break;
          case 'INVALID_PAGINATION':
            // Handle a negative first/last
            displayValidationErrors(error.message);
            break;
          default:
            // Handle other errors
            logError(error);
            displayGenericErrorMessage();
        }
      });
    }
    
    return result.data;
  } catch (error) {
    // Handle network errors
    logError(error);
    displayNetworkErrorMessage();
    return null;
  }
}
```

## Best practices

Never assume a GraphQL response won't contain errors, so always check for them. GraphQL can return partial data with errors for some fields, so handle partial data. Translate error messages into actionable feedback for users, automatically retry after authentication failures, and capture detailed information about unexpected errors for debugging.
