Errors

Errors in bulk actions

{
  total: number,
  page: number,
  pageSize: number,
  pageResults: [
   ...
  ],
	errors: [string]
}

Bemmbo API bulk errors are handled in an errors field in the response body. Which can be.

  • ${issuerFiscalId/customerFiscalId} not found: The RUT of the supplier/customer, contributor was not found.
  • Unexpected error retrieving ${issuerFiscalId/customerFiscalId}: The data of the supplier, customer is wrong.
  • Unexpected errors retrieving invoices: We did something wrong.

Why bring errors in a field? → So the whole request does not fail if one of the customers/vendors is wrong and they can work partially with the right data. Here it is a example handling partial errors.

// Define the API base URL and endpoint
const baseURL = 'https://api.bemmbo.com/v1/invoices';
const endpoint = '/issued';

// Define the query parameters
const queryParams = new URLSearchParams({
  status: 'ISSUED,PAID', // Filter by statuses 'ISSUED' and 'PAID'
  dueDateSince: '2024-01-01', // Filter invoices due from Jan 1, 2024
  dueDateUntil: '2024-09-01', // Filter invoices due until Sep 1, 2024
  options_page: '1', // Page number
  options_pageSize: '50', // Number of results per page
});

// Define the full URL with query parameters
const url = `${baseURL}${endpoint}?${queryParams.toString()}`;

// Fetch API token (this should be stored securely)
const apiToken = 'your_token_goes_here';

// Function to handle errors and take actions
function handleErrors(errors) {
  errors.forEach((error) => {
    console.error('API Error:', error);

    // Check for specific error types and handle them accordingly
    if (error.includes('not found')) {
      console.warn('Warning: Customer or Invoice not found:', error);
      // Optionally, take some recovery action for missing customer/invoice
    } else if (error.includes('Unexpected error retrieving')) {
      console.warn('Error retrieving data:', error);
      // Retry the request or log the issue for further investigation
    } else {
      console.warn('Other error:', error);
      // General error handling
    }
  });
}

// Function to fetch issued invoices
async function fetchIssuedInvoices() {
  try {
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': apiToken,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error(`Error: ${response.status} - ${response.statusText}`);
    }

    const data = await response.json();

    // Check if there are errors in the response
    if (data.errors && data.errors.length > 0) {
      handleErrors(data.errors);
    } else {
      // Process the response data (log the results)
      console.log('Total Invoices:', data.total);
      console.log('Invoices on Current Page:', data.pageResults);

      // Example: Iterate over the invoices and print some

import requests

# Definir la URL base de la API y el endpoint
base_url = 'https://api.bemmbo.com/v1/invoices'
endpoint = '/issued'

# Definir los parámetros de consulta
query_params = {
    'status': 'ISSUED,PAID',  # Filtrar por los estados 'ISSUED' y 'PAID'
    'dueDateSince': '2024-01-01',  # Filtrar facturas con vencimiento desde el 1 de enero de 2024
    'dueDateUntil': '2024-09-01',  # Filtrar facturas con vencimiento hasta el 1 de septiembre de 2024
    'options_page': '1',  # Número de página
    'options_pageSize': '50'  # Número de resultados por página
}

# Definir el token de autenticación
api_token = 'your_token_goes_here'

# Función para manejar errores y tomar acciones
def handle_errors(errors):
    for error in errors:
        print(f'API Error: {error}')
        
        # Manejar diferentes tipos de errores
        if 'not found' in error:
            print('Advertencia: Cliente o factura no encontrada:', error)
            # Puedes realizar alguna acción de recuperación aquí
        elif 'Unexpected error retrieving' in error:
            print('Error inesperado al recuperar datos:', error)
            # Se podría intentar un reintento o registrar el error para investigación
        else:
            print('Otro error:', error)
            # Manejo general de errores

# Función para obtener las facturas emitidas
def fetch_issued_invoices():
    try:
        # Hacer la solicitud GET a la API
        headers = {
            'Authorization': api_token,
            'Content-Type': 'application/json'
        }
        response = requests.get(f'{base_url}{endpoint}', headers=headers, params=query_params)

        # Verificar si la solicitud fue exitosa
        if response.status_code != 200:
            raise Exception(f'Error: {response.status_code} - {response.reason}')

        # Obtener los datos en formato JSON
        data = response.json()

        # Verificar si hay errores en la respuesta
        if 'errors' in data and data['errors']:
            handle_errors(data['errors'])
        else:
            # Procesar los datos de la respuesta
            print