Skip to main content

Overview

The DonaSF API implements consistent error handling across all layers, from database operations through business logic to HTTP responses. Understanding these patterns is essential for proper API integration and troubleshooting.

Error Response Format

All API endpoints return errors in a consistent format:

Standard Error Response

{
  "error": "Error description message"
}
For more complex errors, especially from queries:
{
  "mensaje": "Detailed error message"
}

Success Response with Result Flag

Many endpoints return a result flag to indicate success/failure:
{
  "Resultado": false,
  "Mensaje": "No se encontró el registro"
}

HTTP Status Codes

The API uses standard HTTP status codes to indicate the outcome of requests:

200 OK

Request succeeded. Returns data or success message.

400 Bad Request

Invalid input, missing parameters, or business rule violation.

404 Not Found

Requested resource does not exist in the database.

500 Internal Server Error

Unhandled exception or database connection failure (implicit).

Error Handling by Layer

Controller Layer (API)

Controllers validate input and transform business layer errors into HTTP responses.

Input Validation Errors

Missing Required Parameters:
if (string.IsNullOrEmpty(identificador))
    return BadRequest("Proporcione datos al Identificador");

if (string.IsNullOrWhiteSpace(identificador))
    return BadRequest("Proporcione datos al identificador");
Response:
HTTP 400 Bad Request
"Proporcione datos al Identificador"

Business Logic Errors

Error from Business Layer:
var resultados = new BDonacion().CrearDonacion(jSONDonacionL);
if (!string.IsNullOrEmpty(resultados.error))
    return BadRequest($"Error {resultados.error}");
Response:
HTTP 400 Bad Request
"Error: Cannot insert duplicate key"

Data Not Found Errors

Empty Result Set:
DataTable tabla = resultados.informacion as DataTable;

if (tabla == null || tabla.Rows.Count == 0)
    return NotFound("No se encontraron Datos");
Response:
HTTP 404 Not Found
"No se encontraron Datos"
Result Flag Check:
bool donacionEncontrada = tabla.Rows[0].Field<bool>("Resultado");

if (!donacionEncontrada)
{
    return NotFound(new
    {
        mensaje = tabla.Rows[0]["resultados"].ToString()
    });
}
Response:
HTTP 404 Not Found
{
  "mensaje": "No se encontró la donación con el identificador proporcionado"
}

Exception Handling

Try-Catch Wrapper:
try
{
    // Validation and business logic
}
catch(Exception ex)
{
    return BadRequest($"Error al buscar la donacion {ex.Message}");
}
Response:
HTTP 400 Bad Request
"Error al buscar la donacion: Connection timeout"

Business Logic Layer

Business logic classes catch exceptions and return errors via InfoCompartidaCapas.

Standard Pattern

public InfoCompartidaCapas CrearDonacion(JSONDonacionL jSONDonacionL)
{
    InfoCompartidaCapas info = new InfoCompartidaCapas();
    try
    {
        IDMDonacion consulta = new CDMDonacion(new DMDonacion());
        DataTable tabla = consulta.CrearDonacion(jSONDonacionL);
        info.informacion = tabla;
        info.error = null;  // Success
    }
    catch (Exception ex)
    {
        info.informacion = null;
        info.error = ex.Message;  // Error captured
    }
    return info;
}

Error Propagation

Errors from the data layer are caught and propagated through InfoCompartidaCapas.error:
public class InfoCompartidaCapas
{
    public object? informacion { get; set; }
    public string? error { get; set; }
}

Data Access Layer

The data layer handles SQL exceptions and connection errors.

Connection Errors

try
{
    ConectarSinTransaccion();
    consulta.ExecuteNonQuery();
    DesconectarSinTransaccion();
    return new InfoCompartidaCapas() { informacion = true };
}
catch (Exception ex)
{
    DesconectarSinTransaccionError();
    throw;  // Propagate to business layer
}

SQL Exceptions

SQL Server exceptions (constraint violations, deadlocks, etc.) are thrown and caught in the business layer.

Common Error Scenarios

1. Invalid Input Parameters

POST /Misionero/CrearMisionero
{
  "nombre": "",
  "correo": "[email protected]"
}

2. Resource Not Found

GET /Claves/VerClaveDonativo?identificador=999

3. Duplicate Entry

POST /Claves/CrearClaveDonativo
{
  "codigo": "X",
  "cantidad": 10.00
}

4. Database Connection Failure

GET /Donacion/VerDonaciones?identificador=123

5. Foreign Key Constraint Violation

POST /Misionero/CrearMisionero
{
  "nombre": "Juan Pérez",
  "idadmin": 999
}

6. Data Operation Failure

POST /Talones/CrearTalones
{
  "folio": 12345,
  "idclave": 1
}

7. Server Communication Error

POST /Admin/VerAdministrador?identificador=abc

Error Handling Best Practices

Always check resultados.error immediately after calling business logic methods:
var resultados = new BDonacion().CrearDonacion(jSONDonacionL);
if (!string.IsNullOrEmpty(resultados.error))
    return BadRequest($"Error {resultados.error}");
Always check if DataTable is null or empty before accessing rows:
DataTable tabla = resultados.informacion as DataTable;
if (tabla == null || tabla.Rows.Count == 0)
    return NotFound("No se encontraron datos");
When reading BIT (boolean) columns from SQL Server, use Field<bool>() to avoid casting errors:
bool adminencontrado = tabla.Rows[0].Field<bool>("Resultado");
Use try-catch blocks in controllers for operations with multiple steps:
try
{
    // Validation and processing
}
catch (Exception ex)
{
    return BadRequest($"Error: {ex.Message}");
}
Provide context in error messages to help clients understand what went wrong:
return BadRequest($"Error al buscar el Administrador: {ex.Message}");
Check for null responses from business layer before processing:
if (resultados == null)
    return BadRequest("No se obtuvo respuesta del servidor");

Debugging Errors

Reading Error Messages

Error messages follow specific patterns based on the source:
Error: ...
string
Business logic or validation error from the business layer
No se ...
string
Spanish error message indicating a failed operation or missing data
Error al ...
string
Exception caught during a specific operation (e.g., “Error al buscar”)
Proporcione ...
string
Missing or invalid input parameter

Common SQL Server Errors

Error PatternCauseSolution
UNIQUE KEY constraintDuplicate value in unique columnCheck for existing records before insert
FOREIGN KEY constraintReferenced record doesn’t existVerify parent record exists
CHECK constraintValue violates check ruleReview constraint rules (e.g., folio_inicio < folio_fin)
Cannot insert NULLRequired field is nullProvide all required fields
Connection timeoutDatabase unreachableCheck connection string and network

Build docs developers (and LLMs) love