NueForm

Gestion des erreurs

Comprendre le format des réponses d'erreur de l'API NueForm, les codes d'erreur et comment gérer les erreurs dans votre application.

L'API NueForm utilise les codes de statut HTTP conventionnels et renvoie des réponses d'erreur JSON structurées. Ce guide couvre le format de réponse, tous les codes d'erreur possibles et les modèles pour gérer les erreurs dans votre code.

Formats de réponse

Réponses de succès

Successful API calls return a JSON object with a data field. List endpoints also include a meta field with pagination information.

json
{
  "data": {
    "id": "clx1abc2d3e4f5g6h7i8j9k0",
    "title": "Customer Feedback",
    "status": "published",
    "created_at": "2026-01-15T09:30:00.000Z"
  }
}

With pagination metadata:

json
{
  "data": [
    {
      "id": "clx1abc2d3e4f5g6h7i8j9k0",
      "title": "Customer Feedback"
    },
    {
      "id": "clx2def3g4h5i6j7k8l9m0n1",
      "title": "Employee Survey"
    }
  ],
  "meta": {
    "page": 1,
    "per_page": 20,
    "total": 150,
    "total_pages": 8
  }
}

Réponses d'erreur

Error responses return a JSON object with an error field containing the error code, a human-readable message, and the HTTP status code.

json
{
  "error": {
    "code": "NOT_FOUND",
    "message": "The requested form could not be found.",
    "status": 404
  }
}

Codes d'erreur

The following table lists all error codes returned by the API:

CodeHTTP StatusDescription
BAD_REQUEST400The request is malformed, missing required fields, or contains invalid values.
UNAUTHORIZED401Authentication failed. The API key is missing, malformed, revoked, or expired.
FORBIDDEN403The authenticated user does not have permission to perform this action.
NOT_FOUND404The requested resource does not exist or is not accessible to the authenticated user.
CONFLICT409The request conflicts with the current state of the resource (e.g., duplicate entry).
RATE_LIMITED429Too many requests. See Rate Limits for details.
INTERNAL_ERROR500An unexpected error occurred on the server.

Exemples de réponses d'erreur

400 Bad Request

Returned when the request body is invalid or required fields are missing.

json
{
  "error": {
    "code": "BAD_REQUEST",
    "message": "Field 'title' is required.",
    "status": 400
  }
}

401 Unauthorized

Returned when authentication fails for any reason.

json
{
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or expired API key.",
    "status": 401
  }
}

403 Forbidden

Returned when the user is authenticated but lacks permission. Common causes include accessing another user's resources or using a feature not available on the current plan.

json
{
  "error": {
    "code": "FORBIDDEN",
    "message": "API access is not available on your current plan.",
    "status": 403
  }
}

404 Not Found

Returned when the requested resource does not exist.

json
{
  "error": {
    "code": "NOT_FOUND",
    "message": "The requested form could not be found.",
    "status": 404
  }
}

409 Conflict

Returned when the request would create a duplicate or conflicts with existing data.

json
{
  "error": {
    "code": "CONFLICT",
    "message": "A form with this slug already exists.",
    "status": 409
  }
}

429 Rate Limited

Returned when the rate limit has been exceeded. Includes a Retry-After header.

json
{
  "error": {
    "code": "RATE_LIMITED",
    "message": "Rate limit exceeded. Please try again later.",
    "status": 429
  }
}

500 Internal Error

Returned when an unexpected server error occurs. If this persists, contact support.

json
{
  "error": {
    "code": "INTERNAL_ERROR",
    "message": "An internal error occurred.",
    "status": 500
  }
}

Gérer les erreurs dans le code

JavaScript

Build a reusable API client that checks for errors and throws typed exceptions:

javascript
class NueFormApiError extends Error {
  constructor(code, message, status) {
    super(message);
    this.name = "NueFormApiError";
    this.code = code;
    this.status = status;
  }
}

async function nueformRequest(path, options = {}) {
  const response = await fetch(`https://app.nueform.com/api/v1${path}`, {
    ...options,
    headers: {
      "Authorization": `Bearer ${process.env.NUEFORM_API_KEY}`,
      "Content-Type": "application/json",
      ...options.headers,
    },
  });

  const body = await response.json();

  if (!response.ok) {
    const { code, message, status } = body.error;
    throw new NueFormApiError(code, message, status);
  }

  return body;
}

// Usage
async function getForm(formId) {
  try {
    const { data } = await nueformRequest(`/forms/${formId}`);
    return data;
  } catch (error) {
    if (error instanceof NueFormApiError) {
      switch (error.code) {
        case "NOT_FOUND":
          console.error(`Form ${formId} does not exist.`);
          return null;
        case "UNAUTHORIZED":
          console.error("Check your API key configuration.");
          break;
        case "RATE_LIMITED":
          console.warn("Rate limited. Implement backoff and retry.");
          break;
        default:
          console.error(`API error [${error.code}]: ${error.message}`);
      }
    }
    throw error;
  }
}

Python

python
import os
import requests

class NueFormApiError(Exception):
    def __init__(self, code, message, status):
        super().__init__(message)
        self.code = code
        self.status = status

class NueFormClient:
    def __init__(self, api_key=None):
        self.api_key = api_key or os.environ["NUEFORM_API_KEY"]
        self.base_url = "https://app.nueform.com/api/v1"

    def request(self, method, path, **kwargs):
        url = f"{self.base_url}{path}"
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json",
        }

        response = requests.request(method, url, headers=headers, **kwargs)
        body = response.json()

        if not response.ok:
            error = body["error"]
            raise NueFormApiError(
                error["code"], error["message"], error["status"]
            )

        return body

# Usage
client = NueFormClient()

try:
    result = client.request("GET", f"/forms/{form_id}")
    form = result["data"]
    print(f"Form: {form['title']}")

except NueFormApiError as e:
    if e.code == "NOT_FOUND":
        print(f"Form {form_id} does not exist.")
    elif e.code == "UNAUTHORIZED":
        print("Check your API key configuration.")
    elif e.code == "RATE_LIMITED":
        print("Rate limited. Implement backoff and retry.")
    else:
        print(f"API error [{e.code}]: {e}")

Meilleures pratiques

Toujours vérifier le champ error

Never assume a response is successful based on the presence of a body alone. Always check for the error field or verify the HTTP status code before processing the response.

Utiliser des codes d'erreur spécifiques pour le flux de contrôle

Match on error.code (e.g., NOT_FOUND, RATE_LIMITED) rather than the HTTP status code. Error codes are stable, descriptive, and easier to reason about in application logic.

Journaliser les détails des erreurs

Include the full error response in your logs for debugging. The code, message, and status together provide enough context to diagnose most issues without reproducing the request.

Gérer les erreurs 5xx avec des tentatives

Server errors (500 Internal Error) are typically transient. Implement retry logic with exponential backoff for these responses. Limit retries to 2--3 attempts before failing.

Ne pas exposer les messages d'erreur aux utilisateurs finaux

API error messages are designed for developers, not end users. Map API errors to user-friendly messages in your application.

If you receive persistent 500 Internal Error responses, please contact support with the request details and timestamps. Server errors are logged on our end and investigated.

Dernière mise à jour : 6 avril 2026