> For the complete documentation index, see [llms.txt](https://docs.pyck.cloud/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.pyck.cloud/graphql-api/error-handling.md).

# Error Handling

GraphQL Error Handling

## Overview

Understanding how to handle errors in the pyck GraphQL API is essential for building robust applications. 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",
        "details": { ... }
      }
    }
  ]
}
```

## Common Error Codes

pyck uses standardized error codes to help you identify and handle specific error conditions:

* `UNAUTHENTICATED`: The request lacks valid authentication
* `FORBIDDEN`: The authenticated user doesn't have sufficient permissions
* `BAD_USER_INPUT`: The request contains invalid input values
* `NOT_FOUND`: The requested resource was not found
* `CONFLICT`: The operation would conflict with current state
* `INTERNAL_SERVER_ERROR`: An unexpected error occurred on the server

## Error Handling Strategies

### Authentication Errors

When you receive `UNAUTHENTICATED` errors:

* 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 receive `FORBIDDEN` errors:

* 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

### Input Validation Errors

When you receive `BAD_USER_INPUT` errors:

* Check the `details` field in the error extensions for specifics
* Validate input data before sending it to the API
* Display helpful error messages to guide users

### Not Found Errors

When you receive `NOT_FOUND` errors:

* Verify that you're using the correct ID
* Check if the resource might have been deleted
* Consider graceful degradation or fallback options

### Conflict Errors

When you receive `CONFLICT` errors:

* Refresh your local data to see the current state
* Resolve the conflict by merging changes or taking alternative actions
* Consider optimistic UI with conflict resolution

## Error Handling Example

Here's an example of how to handle errors in a client application:

```javascript
async function executeGraphQLQuery(query, variables) {
  try {
    const response = await fetch('https://api.pyck.ai/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 'UNAUTHENTICATED':
            // Handle authentication error (e.g., refresh token)
            refreshAuthToken();
            break;
          case 'FORBIDDEN':
            // Handle permission error
            notifyUserOfPermissionIssue(error.message);
            break;
          case 'BAD_USER_INPUT':
            // Handle validation error
            displayValidationErrors(error.extensions?.details);
            break;
          default:
            // Handle other errors
            logError(error);
            displayGenericErrorMessage();
        }
      });
    }
    
    return result.data;
  } catch (error) {
    // Handle network errors
    logError(error);
    displayNetworkErrorMessage();
    return null;
  }
}
```

## Best Practices

1. **Always check for errors**: Never assume a GraphQL response won't contain errors
2. **Handle partial data**: GraphQL can return partial data with errors for some fields
3. **Provide user feedback**: Translate error messages into actionable feedback
4. **Implement retry logic**: Automatically retry after authentication failures
5. **Log unexpected errors**: Capture detailed information for debugging


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.pyck.cloud/graphql-api/error-handling.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
