Exception Listeners

❗ Exception Listeners

In a distributed or asynchronous messaging system, things can go wrong: a handler might throw an error, a payload might be malformed, or some service dependency might fail. That’s where Exception Listeners come in.

The @nestjstools/messaging package provides a powerful way to centrally manage and respond to unhandled exceptions thrown during message processing.


🔍 What is an Exception Listener?

An Exception Listener allows you to hook into the lifecycle of message processing and respond when any uncaught exception occurs during handling.

This is useful for:

  • Logging errors

  • Triggering alerting or monitoring workflows

  • Performing recovery logic or fallback strategies

  • Retrying logic (manual or delegated)


🛠️ How to Create One

To define an exception listener:

  1. Implement the ExceptionListener interface

  2. Decorate the class with @MessagingExceptionListener()

Example:

import { Injectable } from '@nestjs/common';
import {
  ExceptionListener,
  MessagingExceptionListener,
  ExceptionContext,
} from '@nestjstools/messaging';

@Injectable()
@MessagingExceptionListener()
export class CustomExceptionListener implements ExceptionListener {
  async onException(context: ExceptionContext): Promise<void> {
    console.log(`Exception caught during message handling:`, context.error);

    // Optional: Log to external services, trigger notifications, retry logic, etc.
  }
}

🧠 How It Works

  • If an exception is thrown in any message handler or middleware during message execution:

    • It is propagated up to the listener

    • The onException(context) method is invoked with detailed metadata

The ExceptionContext includes:

Field
Description

error

The exception that was thrown

message

The message that caused the failure

channelName

The name of the channel where the error occurred

handler

(Optional) The handler class involved, if available

raw

Raw data passed to the channel before deserialization


Summary

Feature
Description

🧹 Centralized Handling

Avoid scattering try/catch blocks in every handler

🔁 Recovery Support

Trigger fallback, retries, or compensating transactions

📈 Observability

Report to monitoring tools like Sentry, Datadog, or Logstash

🛠 Cleaner Code

Keep message handlers focused on business logic

Last updated