@onlineapps/error-handler-core
v4.0.0
Published
Core error handling functionality for OA Drive microservices - classification, retry, circuit breaker, DLQ routing
Downloads
5,368
Maintainers
Readme
Status: current Owns: the platform's error handling itself — classification, retry, circuit breaker and compensation
Uniform: library/connector
Duty sections that apply:
all: L-MAIN, L-ENGINES, L-TESTS, L-TEST-SCRIPT, L-PACK-TESTS, L-PINS, L-NO-FILE-RANGE, L-CHANGELOG, L-README, L-README-REGION, L-CONSUMERconnector: L-CONNECTOR-ENV
@onlineapps/error-handler-core
Core error handling functionality for OA Drive microservices. Used by both business services (via conn-infra-error-handler wrapper) and infrastructure services (directly).
Features
- Error Classification - Automatic error type detection (TRANSIENT, BUSINESS, FATAL, etc.)
- Retry Logic - Exponential backoff for transient errors
- Circuit Breaker - Protection against cascading failures
- Compensation - Rollback operations for failed workflows
- Unified Logging - Structured error logging via monitoring-core
Installation
npm install @onlineapps/error-handler-coreUsage
Basic Setup
const { init: initMonitoring } = require('@onlineapps/monitoring-core');
const { ErrorHandlerCore } = require('@onlineapps/error-handler-core');
// Initialize monitoring-core
const monitoring = await initMonitoring({
serviceName: 'my-service',
mode: 'light'
});
// Initialize error handler
const errorHandler = new ErrorHandlerCore({
serviceName: 'my-service',
serviceVersion: '1.0.0',
environment: process.env.NODE_ENV,
monitoring: monitoring, // monitoring-core instance (required)
handling: {
maxRetries: 3,
retryDelay: 1000,
retryMultiplier: 2,
circuitBreakerEnabled: true,
compensationEnabled: true
}
});maxRetries is a budget of attempts, not of retries on top of a first call:
maxRetries: 3 means at most three calls, whichever path drives them —
executeWithRetry() loops three times, and a caller driving the loop itself from
handleError()'s result.shouldRetry stops after the third as well. The other
handling keys, their defaults and their accepted ranges belong to the component
that reads each key (RetryHandler, CircuitBreakerManager); a value outside its
range is refused in the constructor.
Log Error
await errorHandler.logError({
moduleName: 'MyModule',
operation: 'myOperation',
error: new Error('Something failed'),
context: { userId: 123 }
});serviceName (on the handler), moduleName, operation and error are required
inputs, and error must be an Error instance. A missing one is refused with a
message naming it — never renamed to unknown-service / unknown-module /
unknown-operation and never given a substitute message, all of which downstream
reads exactly like the real thing.
Handle Error
try {
await criticalOperation();
} catch (error) {
const result = await errorHandler.handleError({
moduleName: 'MyModule',
operation: 'criticalOperation',
error: error,
context: { operationId: 'op-123' }
});
// result.action: 'retry' | 'dlq' | 'throw' | 'continue' | 'compensate'
// `dlq` is a CLASSIFICATION handed back to the caller: this package publishes
// nothing. A message is dead-lettered by the consumer policy of
// `@onlineapps/mq-client-core` — one rail for biz and infra alike
// (docs/governance/confirmations/mq-consumer-contract.md 002 bod 3).
if (result.action === 'retry') {
await sleep(result.retryDelay);
// Retry operation
}
}It takes the RECORD above, not a bare error. handleError(error) is not a
shorter spelling of handleError({ error }): the same three fields logError()
requires are required here too — moduleName, operation and error — because
handleError() logs before it classifies, through the same UnifiedLogSchema.
context is the only optional key.
A missing one is REFUSED, not defaulted, and the refusal comes from the schema by
the name of the field, checked in that order (moduleName → operation →
error):
[UnifiedLogSchema] Missing required field - "moduleName" must be a non-empty string
naming the module that failed; it is the caller's to provide and is never invented.
Fix: pass params.moduleName (ErrorHandlerCore takes it from errorData.moduleName).So a caller that hands handleError() the caught error itself gets that message
about moduleName — which names the real defect, but only if the reader knows the
call takes a record. Measured by
tests/unit/business-code-outside-the-dictionary.test.js § the call contract.
Execute with Retry
const result = await errorHandler.executeWithRetry({
moduleName: 'MQClient',
operation: 'publish',
fn: async () => await mqClient.publish(queue, message),
context: { queue, messageId }
});Execute with Circuit Breaker
const result = await errorHandler.executeWithCircuitBreaker({
moduleName: 'ExternalAPI',
operation: 'getUser',
circuitName: 'user-api',
fn: async () => await userAPI.getUser(id),
context: { userId: id }
});An open circuit refuses with CircuitOpenError — a type, not a sentence, because
this is the one refusal a client sees verbatim (INFRA-DOCS audit P5, point 7):
const { CircuitOpenError } = require('@onlineapps/error-handler-core');
try {
await errorHandler.executeWithCircuitBreaker('user-api', fn);
} catch (error) {
if (error.code === 'CIRCUIT_OPEN') {
// error.details.name === 'user-api'; error instanceof CircuitOpenError
}
throw error;
}Branch on error.code, never on error.message: the wording follows
.claude/rules/architecture-principles.md §5 and may be improved, the code and
details.name are the contract.
DECLINED — a rule forbade the work
Every class in ErrorTypes names a way the work FAILED, except this one. DECLINED
says the work was refused: the domain rule that was asked says it must not happen —
a document already sent, an item the source will not discuss. It is terminal, it is
not a failure, it is not retried and it is not dead-lettered; ErrorHandlerCore
answers it with the verdict declined, which — like dlq — is a classification
returned to the caller, not a route this package takes.
It is declared by the THROWER, through error.type, and never derived from a status:
every other 409 stays BUSINESS, table and all. That is deliberate, because the
same status carries both meanings and only the thrower knows which one it meant.
@see api/docs/governance/confirmations/workflow-failed-status-projection.md — 004 @see api/docs/biz/70-contracts/error-handling.md — the error classes
Which codes the classifier answers for
ErrorClassifier reads three things and nothing else: this package's own
ErrorTypes (error.type), Node's network codes (ECONNREFUSED, ETIMEDOUT, …)
and HTTP status codes (error.code / error.status) — so 502, 503 and
504 carry their HTTP meaning here. AMQP reply codes share those numbers with a
different meaning, and they have a different owner: a publish failure is
classified inside the transport, before the error leaves it.
@see api/shared/mq-client-core/src/utils/publishErrors.js
Measured by tests/unit/classified-domains-one-owner.test.js: the table's numeric
keys are HTTP status codes, and the AMQP reply codes HTTP does not use (406,
530, 405, …) are not keys of it.
A business code this table does not know
The classifier neither labels nor refuses it. A business name it has never heard
of — REFERENCE_RECORD_MISSING, say — simply misses the code lookup, and the class
comes from the next thing the error declares: error.type, then error.code in the
table, then error.status. So an unknown name at 422 is VALIDATION, exactly like
a bare 422; the same unknown name at 503 is TRANSIENT. Two different unknown
names with one status get one class, because the name is not read at all.
retryable is not read here either. It belongs to the error contract and is consumed
elsewhere (ErrorMapper.CONTRACT_RETRYABLE_CODES, the dispatcher's _canRetry); on
this classifier it changes nothing, and whether a retry happens follows from the
CLASS (ErrorHandlerCore._decideAction: TRANSIENT/TIMEOUT/RATE_LIMIT retry,
BUSINESS/VALIDATION do not).
This is a rule, not an omission: the dictionary of business code NAMES is not this
package's to own. It lives in api/docs/biz/70-contracts/error-handling.md §1
(BIZ-DOCS), and a new name is agreed through the process error-code-dictionary 002.
A name branch here would make the class depend on a dictionary this package cannot
see, which is two owners of one fact (change-discipline.md § One rail per concern).
Measured 2026-09-22 (d.803): nothing in the workspace marks a business code as
"unknown" — the only machine-readable code list is CONTRACT_RETRYABLE_CODES, which
is the retryable set and nothing else.
Measured by tests/unit/business-code-outside-the-dictionary.test.js, including the
control that the table really does not carry the name.
API Reference
See ERROR_HANDLING.md for the cross-cutting standard (classification table, fail-loudly rules).
Architecture
- Core Library - Used directly by infrastructure services
- Wrapper -
conn-infra-error-handlerwraps this for business services - Dependencies - Uses
monitoring-corefor logging
Related Documentation
License: MIT
