Skip to content

GermanVR-Mulesoft/global-error-handler-lib

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Mule Global Error Handler Library

Biblioteca reutilizable para Mule 4 que proporciona un Global Error Handler (GHE) estandarizado para arquitecturas API-Led Connectivity (SAPI, PAPI y EAPI).

El objetivo de esta librería es centralizar el manejo de errores técnicos, permitir la propagación entre capas y mantener un formato uniforme y trazable en toda la plataforma.


Características

  • Manejo centralizado de errores comunes.
  • Compatibilidad con SAPI, PAPI y EAPI.
  • Propagación automática de errores entre capas.
  • Soporte para sobrescribir namespace, identifier, description y details.
  • Preserva el correlationId para trazabilidad.
  • Construcción automática del errorChain.
  • Permite ocultar detalles técnicos al consumidor final.
  • Compatible con errores provenientes de:
    • APIKit
    • HTTP Request
    • Database
    • Salesforce
    • SAP
    • Cualquier conector Mule
  • Fácil integración mediante dependencia Maven.
  • Separación entre errores técnicos y errores de negocio.

Estructura del proyecto

global-error-handler-lib/

README.md
LICENSE

src/

└── main
    ├── mule
    │     global-error-handler-lib.xml
    │
    └── resources
          └── modules
          │     common.dwl
          │     extract_details.dwl
          │     normalize_identifier.dwl
          └── config
                ghe-config.yaml

Arquitectura soportada

Cliente
   ↓

EAPI
   ↓

PAPI
   ↓

SAPI
   ↓

Sistema externo

Ejemplo:

WEB-EAPI
   ↓

POLICY-PAPI
   ↓

SALESFORCE-SAPI
   ↓

Salesforce

Formato de respuesta

Ejemplo:

{
  "correlationId": "9f6c4b51-42c4-11ef-b1f5-0242ac120002",
  "timestamp": "2026-06-13T12:15:00Z",
  "namespace": "WEB-EAPI",
  "identifier": "INTERNAL_SERVER_ERROR",
  "description": "Unexpected error",
  "details": "Connection timeout",
  "errorChain": [
    {
      "namespace": "WEB-EAPI",
      "identifier": "INTERNAL_SERVER_ERROR"
    },
    {
      "namespace": "POLICY-PAPI",
      "identifier": "INTERNAL_SERVER_ERROR"
    },
    {
      "namespace": "SALESFORCE-SAPI",
      "identifier": "TIMEOUT"
    },
    {
      "namespace": "SALESFORCE",
      "identifier": "TIMEOUT"
    }
  ]
}

Filosofía del diseño

La librería:

  • Maneja errores técnicos.
  • Propaga errores entre capas.
  • No contiene reglas de negocio.

Los errores funcionales o de negocio pertenecen a cada API consumidora.


Instalación

Agregar dependencia:

<dependency>
    <groupId>com.github.germanvr</groupId>
    <artifactId>global-error-handler-lib</artifactId>
    <version>1.0.0</version>
    <classifier>mule-plugin</classifier>
</dependency>

Uso

Referenciar el handler:

<error-handler ref="global-error-handler-lib"/>

Configuración

Cada API define únicamente sus propiedades.

SAPI

app:
  namespace:
    current: GERMANVR-EX-SAPI
    client: HTTP_BIN
    
  metadata:
    showApplication: "true"
    showErrorChain: "true"
    showDetails: "true"

PAPI

app:
  namespace:
    current: GERMANVR-EX-PAPI
    
  metadata:
    showApplication: "true"
    showErrorChain: "true"
    showDetails: "true"

EAPI

# GLOBAL ERROR HANDLER LIB CONFIGURATION
app:
  namespace:
    current: GERMANVR-EX-EAPI
    
  metadata:
    showApplication: "false"
    showErrorChain: "false"
    showDetails: "false"
    

Variables soportadas

vars.errorConfig

Variable opcional que permite personalizar la respuesta.

Ejemplo:

<set-variable variableName="errorConfig"
value='#[{
    httpStatus: 500,
	  identifier: "ERR_1003",
  	description: "Error al procesar la solicitud",
  	details: "Su solicitud no puedo ser atendida en este momento"
}]'/>

Comportamiento de details

Valor Resultado
null Hereda el valor anterior
"" Oculta el campo
valor Reemplaza el valor

Propagación entre capas

SAPI

Genera:

GERMANVR-EX-SAPI → BIN_ORG

PAPI

Propaga:

GERMANVR-EX-PAPI → GERMANVR-EX-SAPI → BIN_ORG

EAPI

Propaga:

GERMANVR-EX-EAPI → GERMANVR-EX-PAPI → GERMANVR-EX-SAPI → BIN_ORG

ErrorChain

El errorChain contiene todas las capas involucradas.

Ejemplo:

  [
      {
          "namespace": "GERMANVR-EX-PAPI",
          "identifier": "NOT_FOUND",
          "description": "HTTP GET on resource 'http://localhost:8085/papi' failed: not found (404).",
          "failingComponent": "germanvr-papi-client/processors/0 @ germanvr-example-eapi:clients/germanvr-ex-papi-client.xml:11 (Request to PAPI)"
      },
      {
          "namespace": "GERMANVR-EX-SAPI",
          "identifier": "NOT_FOUND",
          "description": "HTTP GET on resource 'http://localhost:8081/sapi' failed: not found (404).",
          "failingComponent": "sapi-bin-client/processors/0 @ germanvr-example-papi:clients/germanvr-ex-sapi-client.xml:11 (Request to SAPI)"
      },
      {
          "namespace": "BIN_ORG",
          "identifier": "NOT_FOUND",
          "description": "HTTP GET on resource 'https://httpbin.org:443/status/404' failed: not found (404).",
          "failingComponent": "get-httpbin-client/processors/0 @ germanvr-example-sapi:clients/httpbin-client.xml:11 (Request to LEGACY SYSTEM)"
      }
  ]

Esto facilita:

  • Troubleshooting.
  • Observabilidad.
  • Análisis de causa raíz.
  • Integración con Splunk, Datadog o Anypoint Monitoring.

Errores APIKit soportados

La librería maneja automáticamente:

  • APIKIT:BAD_REQUEST → 400
  • APIKIT:NOT_FOUND → 404
  • APIKIT:METHOD_NOT_ALLOWED → 405
  • APIKIT:NOT_ACCEPTABLE → 406
  • APIKIT:UNSUPPORTED_MEDIA_TYPE → 415
  • APIKIT:NOT_IMPLEMENTED → 501
  • ANY → 500

Errores de negocio

La librería NO incluye reglas de negocio.

Se recomienda crear un handler independiente por proyecto.

Ejemplo:

<choice>

    <when expression="#[isEmpty(payload)]">

        <set-variable variableName="errorConfig"
        value='#[{
            namespace: "CUSTOMER",
            identifier: "NOT_FOUND",
            description: "Customer not found",
            details: ""
        }]'/>

        <set-variable variableName="permanentError"
        value="true"/>

        <set-payload value='#[{
            httpStatus: 404
        }]'/>

        <raise-error type="BUSINESS:ERROR"/>

    </when>

</choice>

El flujo sería:

Business Handler
       ↓
Raise Error
       ↓
Global Error Handler Library

Recomendaciones

SAPI

  • Conectarse a un único sistema.
  • No implementar lógica de negocio.
  • Mapear errores funcionales del sistema externo.

PAPI

  • Orquestar múltiples SAPIs.
  • Personalizar mensajes para consumidores internos.

EAPI

  • Adaptar la respuesta para consumidores finales.
  • Ocultar detalles técnicos cuando sea necesario.

Buenas prácticas

  • Mantener nombres de namespace estables entre ambientes.
  • Utilizar correlationId.
  • Evitar exponer información sensible en producción.
  • Centralizar los errores técnicos.
  • Mantener separados los errores de negocio.

Compatibilidad

  • Mule Runtime 4.x
  • Mule Maven Plugin 4.x

Licencia

MIT License.

About

Biblioteca reutilizable para Mule 4 que proporciona un Global Error Handler (GHE) estandarizado para arquitecturas API-Led Connectivity (SAPI, PAPI y EAPI).

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors