Error Handling

Error Handling

Understand API errors and how to handle them gracefully in your applications.

Error Response Format

All errors follow a consistent response format.

{
  "error": {
    "message": "Invalid API key",
    "code": "AUTHENTICATION_ERROR",
    "status": 401
  }
}

message: Human-readable error message

code: Machine-readable error code

status: HTTP status code

Common Error Codes

Reference guide for all error codes and how to handle them.

401 - AUTHENTICATION_ERROR

Invalid or missing API key

429 - RATE_LIMIT_EXCEEDED

Too many requests. Please retry after the specified time.

400 - INVALID_REQUEST

Malformed request or missing required parameters

500 - INTERNAL_ERROR

Server error. Please try again later.

Error Handling Example

Best practices for handling errors in your code.

try {
  const response = await fetch('https://api.nextcraftai.com/v1/chat', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      model: 'google/gemini-2.5-flash',
      messages: [{ role: 'user', prompt: 'Hello!' }]
    })
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(error.error?.message || 'Request failed');
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error('Error:', error.message);
}