Skip to main content

Errors

Use whenyou catch an error from the transport and need to tell causes apart.

You getevery error class, the reason values it carries, and what to do about each.

Each class is named after the area it comes from, Jetstream<Area>Error, and carries a reason that names the exact cause. Catch a whole area with instanceof, or one cause with reason:

import { JetstreamPublishError, PublishErrorReason, isJetstreamError } from '@horizon-republic/nestjs-jetstream';

try {
await firstValueFrom(client.emit('order.placed', order));
} catch (err) {
if (err instanceof JetstreamPublishError && err.reason === PublishErrorReason.StreamFull) {
// back off, alert, or spill to another store
}

if (isJetstreamError(err)) {
logger.error(`${err.name} (${err.reason}): ${err.message}`);
}
}

isJetstreamError() recognises every typed error, JetstreamPublishError included. Prefer it over instanceof when your process may load the package twice, as the CommonJS and ES module builds of one dependency tree can: instanceof fails across the two copies, the guard does not.

All classes except JetstreamPublishError extend the abstract JetstreamBaseError. Match on reason rather than on message text.

At a glance​

ClassThrown whenReason enum
JetstreamConfigErrorModule options or handler declarations are invalid, at startupConfigErrorReason
JetstreamConnectionErrorThe NATS connection is missing or refusedConnectionErrorReason
JetstreamProvisioningErrorThe server refuses to create or update a stream or consumerProvisioningErrorReason
JetstreamBindingErrorExternally managed streams or consumers do not fit your handlersBindingErrorReason
JetstreamMigrationErrorA destructive stream migration is refused or does not finishMigrationErrorReason
JetstreamPublishErrorThe target stream is full and rejects an emit() or send()PublishErrorReason
JetstreamRecordErrorA JetstreamRecordBuilder value or delivery option is invalidRecordErrorReason
JetstreamRpcErrorAn RPC call fails, or RpcContext settlement is misusedRpcErrorReason
JetstreamDeliveryErrorA delivered event cannot be handled; passed to onDeadLetterDeliveryErrorReason
JetstreamScheduleErrorA schedule is refused by the client or the serverScheduleErrorReason
JetstreamCapabilityErrorA feature needs a newer NATS server than the one connectedCapabilityErrorReason

JetstreamPublishError​

ReasonWhenWhat to do
stream-fullThe stream reached max_msgs, max_bytes or max_msgs_per_subject and its policy is discard: newCheck that consumers are running and keeping up, then raise the limits in the stream override.

JetstreamPublishError extends nats.js JetStreamApiError, so code written against the raw nats.js error keeps working: instanceof JetStreamApiError holds, and code, status and message are the server's. The original error is cause. Other publish failures, such as a timeout or no responders, reach you as the nats.js errors they always were.

JetstreamRpcError​

ReasonWhen
timeoutNo reply arrived within the RPC timeout (JetStream RPC mode)
connection-lostThe connection closed for good while the call was pending (JetStream RPC mode)
client-closedThe client closed while the call was pending (JetStream RPC mode)
duplicate-publishThe command's message ID was already used inside the stream's dedup window
decode-failedThe reply could not be decoded and the codec threw a non-Error value
inbox-not-readyThe reply inbox was not subscribed when the command went out
internal-transportThe publish failed unexpectedly; the cause is in the transport's error log
settlement-conflictA handler called both retry() and terminate() on its RpcContext
jetstream-onlyretry() or terminate() was called for a message that did not come from JetStream

In Core RPC mode a timeout is the nats.js TimeoutError, as before.

JetstreamDeliveryError​

Passed as error to onDeadLetter and to the DeadLetter hook, and its message becomes the DLQ x-dead-letter-reason header.

ReasonWhen
no-handlerNo handler is registered for the event's subject
decode-failedThe codec could not decode the payload; the codec's error is cause
retry-on-final-attemptThe handler called retry() on the last delivery max_deliver allows
deliveries-exhaustedThe server stopped redelivering: the handler outlived ack_wait, or the process stopped

An error your handler throws reaches onDeadLetter as is.

JetstreamRecordError​

ReasonWhen
invalid-schedule-datescheduleAt() got an invalid Date
schedule-in-pastscheduleAt() got a date that is not in the future
invalid-ttlttl() got a value that is not a positive finite number
reserved-nats-headersetHeader() targeted a Nats-* header other than Nats-Expected-*, or a record passed one to emit() / send()
reserved-transport-headersetHeader() targeted a header the transport owns, or a record passed one to emit() / send()
schedule-unsupported-for-orderedA record with scheduleAt() was emitted to an ordered: pattern

JetstreamConfigError​

Thrown during startup, so it stops the application before it serves traffic.

ReasonWhen
servers-or-connectionsBoth or neither of servers and connections are set
no-connectionsconnections is empty
no-serversA connection declares no servers
invalid-connection-nameA connection name is empty or has surrounding whitespace
default-connection-requiredNo connection is called default and defaultConnection is not set
unknown-connectionA connection name in defaultConnection, handler extras or a lookup is not configured
duplicate-clusterTwo consuming connections point at the same NATS cluster
publisher-only-connectionA handler is bound to a publisherOnly connection
connections-not-startedconnectJetstreamMicroservices(app) was not called before startAllMicroservices()
stream-ownership-conflictA stream is already owned by another connection of the same service
dlq-unavailableJetstreamDlq was called on a connection whose DLQ stream is off or was never created
dlq-filter-requiredJetstreamDlq.purge() got an empty filter; emptying the whole DLQ is purgeAll()
dlq-filter-invalidA DLQ filter has a sequence bound that is not a non-negative integer, or an invalid date
removed-optionsOptions removed in v3 are still passed
self-target-prefixforFeature() targets the service itself and passes a subjectPrefix
invalid-subject-prefixA subjectPrefix is empty, malformed or contains >
duplicate-handlerTwo handlers declare the same pattern
invalid-handler-patternA pattern has an empty token, whitespace, a > before the last token, or a wildcard that covers schedule holders
ambiguous-handler-patternTwo wildcard handlers of the same kind can match the same subject
conflicting-handler-kindsA handler is declared broadcast and ordered, or scheduled and broadcast or ordered
schedule-on-message-patternA schedule is declared on @MessagePattern
invalid-ack-extensionackExtension.interval or ackExtension.maxDuration is not a positive number
metrics-registry-missingMetrics are enabled but no Prometheus registry was resolved
prometheus-client-missingMetrics are enabled but neither @prometheus-io/client nor prom-client is installed
ambiguous-prometheus-clientBoth Prometheus packages are installed and metrics.register is not set
foreign-registrymetrics.register belongs to neither installed Prometheus package

JetstreamConnectionError​

ReasonWhen
not-connectedunwrap() or a JetStream client was requested before connecting
refusedThe servers refused the connection; the NATS error is cause
closed-while-connectingThe transport closed while its connection was still starting
shutting-downA publish, RPC call or JetStream lookup ran after shutdown began; no new connection is opened

JetstreamProvisioningError​

ReasonWhen
storage-exceededThe reservation exceeds the server's max_file_store or account storage
no-suitable-peersFewer healthy peers than num_replicas, or none with storage headroom
server-rejectedAny other refusal; errCode holds the NATS code

Each error also carries entity, target, kind, errCode, errDescription and a remediation hint.

JetstreamBindingError​

Under provisioning: { management: Manual } the transport checks the streams and consumers you manage against your handlers.

ReasonWhen
consumer-filter-mismatchThe consumer's filter does not cover every registered handler subject
dlq-subject-mismatchThe DLQ stream's subjects do not include the stream name
schedule-subject-mismatchScheduling is enabled but the stream's subjects miss the schedule prefix
consumer-swallows-schedulesThe consumer's filter also matches pending schedule holders
external-consumer-absentThe externally managed consumer is gone; the transport waits for it to return

JetstreamMigrationError​

ReasonWhen
transport-config-conflictThe change touches settings the transport controls, such as retention
schedule-streamThe stream is a schedule stream, which NATS cannot source into
shared-streamThe stream is the broadcast stream other services share
sourcing-timeoutSourcing made no progress for 30 seconds; after the delete, the backup is kept and restored later
peer-timeoutNo longer raised since v3.1: an instance waits for a live migration and takes over an abandoned one
insufficient-capacityThe new max_msgs, max_bytes or max_msgs_per_subject cannot hold what the stream already has; nothing was deleted
lock-lostAnother instance took the migration over; this one stopped before a destructive step
message-schedulesThe stream allows message schedules and holds messages, which NATS cannot source back; nothing was deleted
in-progressConsumer recovery waits for a running migration to finish

See stream migration.

JetstreamScheduleError and JetstreamCapabilityError​

JetstreamScheduleError reasons are listed in recurring schedules. Since 3.1 it also reports leader-change, concurrent-writer and no-schedule-stream, which used to be plain Errors.

JetstreamCapabilityError has a single reason, server-too-old, alongside its capability, requiredLevel and actualLevel fields.