@zudojs/errors
v1.4.0
Published
Shared error base class, error codes, and error handling utilities for the Zudojs framework.
Readme
@zudojs/errors
Shared error base class, error codes, and error handling utilities for the Zudojs framework.
Documentation: zudojs.oyinlola.site/docs/packages-errors · For AI agents: Markdown version, llms.txt
Installation
npm install @zudojs/errorsQuick Start
import {
ApplicationError,
ErrorCode,
serializePublicError,
toBaseError,
} from "@zudojs/errors";
throw new ApplicationError("Something went wrong", {
code: ErrorCode.INTERNAL_ERROR,
statusCode: 500,
metadata: { orderId: "ord_123" },
});
// Anywhere you catch: normalize, enrich, and produce a client-safe body
try {
await work();
} catch (thrown) {
const error = toBaseError(thrown).withMetadata({ requestId });
logger.error(error.toLogObject()); // stack + cause chain, sensitive metadata redacted
res.status(error.statusCode).json(serializePublicError(error));
// -> { code, message, category, statusCode } — no stack, no cause,
// and no metadata unless the error is exposable (or keys are allow-listed)
}Features
BaseErrorwith stablecode,category,severity,statusCode,expose,isOperational, deep-frozenmetadataandcauseErrorCode,ErrorCategoryandErrorSeverityenums with guards (isErrorCode, ...)- Domain, infrastructure and system error families (access, state, HTTP, database, network, container, adapter, crypto, ...) with factories and type guards
- Base classes for other packages' error families, so their
instanceofchecks match:TransactionError(+ 10 subclasses),MiddlewareLimitExceededError/MiddlewareDepthExceededError/MiddlewareRateLimitError/MiddlewareAbortedError,TraversalLimitError,HttpMiddlewareError/HttpMiddlewarePipelineError/HttpRequestGuardError,OpenAPIError,AuthError,OAuthError(withErrorCode.OAUTH_*),CqrsError(+CommandFailedError/QueryFailedError, thrown when a failed command or query result is unwrapped),EventBusStoppedError/EventBusDisposedError(re-exported by@zudojs/events),ObservabilityError,InvalidConstantError/ConstantContextError, and thezudojs-clierrorsCLIValidationError/CLIGenerationError/CLINotInProjectError/CLITemplateError - Serialization limit errors take
{ statusCode?, expose? }as a third argument, so a guard can tell a client that sent too much from a server that built too much.SerializationPayloadTooLargeError(size, maxSize)defaults to an exposed 413 (its message names only the two sizes, soserializePublicErrorreturns it instead of "An unexpected error occurred."); pass{ statusCode: 500, expose: false }for a payload the server built itself, asserializein@zudojs/serializationdoes.SerializationDepthError(depth, maxDepth)defaults to an unexposed 500; guards over untrusted input pass{ statusCode: 400, expose: true } withMetadata()copies any error (including subclasses with custom constructors) with extra metadata- Serialization:
toJSON()/toLogObject()for trusted logs (cycle-safe cause chains truncated with"[MaxDepth]"after 8 levels across the whole chain; metadata under sensitive keys, sensitive keys in object causes and submitted issue values are redacted, soJSON.stringify(error)is safe to log),serializePublicError/ErrorSerializer/ErrorHandler.toPublicResultfor untrusted clients (recursive redaction, metadata allow-list) - Metadata utilities:
createErrorMetadata,mergeErrorMetadata,sanitizeErrorMetadata(drops unsupported values) andredactErrorMetadata(removes secrets) - Normalization (
toBaseError,normalizeUnknownError,ErrorHandler.normalize) that keeps the thrown value ascauseand classifies unknown failures as internal, non-operational 500s - Error mapping registry (
ErrorMapperRegistry,mapErrorType, declarativeErrorMapping) - Cross-package safe type guards (
isBaseErrorrecognises instances from another installed copy of the package)
Use Cases
- Consistent error handling across packages
- HTTP status code mapping
- Error categorization for monitoring
- User-friendly, non-leaking error responses
