Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.triglit.com/llms.txt

Use this file to discover all available pages before exploring further.

Este guia mostra como tratar erros da API do Triglit de forma adequada.

Códigos de Status HTTP

200 OK

Requisição bem-sucedida.

201 Created

Recurso criado com sucesso.

400 Bad Request

Requisição inválida. Verifique os dados enviados.
{
  "statusCode": 400,
  "message": "Validation failed",
  "error": "Bad Request",
  "details": {
    "field": "name",
    "message": "Name is required"
  }
}

401 Unauthorized

Chave de API não fornecida ou inválida.
{
  "statusCode": 401,
  "message": "API key não fornecida. Forneça a chave no header 'X-API-Key'."
}

403 Forbidden

Tipo de chave não permitido ou sem permissão.
{
  "statusCode": 403,
  "message": "Tipo de chave não permitido. Este endpoint aceita apenas: secret key (sk_)."
}

404 Not Found

Recurso não encontrado.
{
  "statusCode": 404,
  "message": "Workflow not found",
  "error": "Not Found"
}

409 Conflict

Conflito (ex: recurso duplicado).
{
  "statusCode": 409,
  "message": "Workflow with this name already exists"
}

429 Too Many Requests

Rate limit excedido.
{
  "statusCode": 429,
  "message": "Rate limit exceeded. Try again in 5 seconds.",
  "error": "Too Many Requests",
  "retryAfter": 5
}

500 Internal Server Error

Erro interno do servidor.
{
  "statusCode": 500,
  "message": "Internal server error",
  "error": "Internal Server Error"
}

Tratamento de Erros

Exemplo em JavaScript

async function handleRequest(requestFn) {
  try {
    const response = await requestFn();
    
    if (!response.ok) {
      const error = await response.json();
      throw new TriglitError(error.statusCode, error.message, error);
    }
    
    return await response.json();
    
  } catch (error) {
    if (error instanceof TriglitError) {
      handleTriglitError(error);
    } else {
      handleNetworkError(error);
    }
    throw error;
  }
}

class TriglitError extends Error {
  constructor(statusCode, message, details) {
    super(message);
    this.statusCode = statusCode;
    this.details = details;
  }
}

function handleTriglitError(error) {
  switch (error.statusCode) {
    case 401:
      console.error('API key inválida. Verifique suas credenciais.');
      break;
    case 403:
      console.error('Sem permissão. Use a chave secreta (sk_) para esta operação.');
      break;
    case 429:
      const retryAfter = error.details.retryAfter || 5;
      console.warn(`Rate limit excedido. Retry após ${retryAfter} segundos.`);
      break;
    case 500:
      console.error('Erro interno do servidor. Tente novamente mais tarde.');
      break;
    default:
      console.error(`Erro ${error.statusCode}: ${error.message}`);
  }
}

Retry com Backoff Exponencial

async function requestWithRetry(requestFn, maxRetries = 3) {
  let lastError;
  
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await requestFn();
    } catch (error) {
      lastError = error;
      
      // Não retry para erros 4xx (exceto 429)
      if (error.statusCode >= 400 && error.statusCode < 500 && error.statusCode !== 429) {
        throw error;
      }
      
      // Backoff exponencial
      const delay = Math.min(1000 * Math.pow(2, attempt), 30000);
      await sleep(delay);
    }
  }
  
  throw lastError;
}

Validação de Dados

Sempre valide dados antes de enviar:
function validateWorkflow(data) {
  const errors = [];
  
  if (!data.name || data.name.trim().length === 0) {
    errors.push('Name is required');
  }
  
  if (data.name && data.name.length > 100) {
    errors.push('Name must be less than 100 characters');
  }
  
  if (errors.length > 0) {
    throw new ValidationError(errors);
  }
  
  return true;
}

Logging

Logue erros para debugging:
async function logError(error, context) {
  await logger.error('Triglit API Error', {
    statusCode: error.statusCode,
    message: error.message,
    context: context,
    timestamp: new Date().toISOString()
  });
}
Implemente tratamento de erros robusto desde o início. Isso facilitará debugging e melhorará a experiência do usuário.