> For the complete documentation index, see [llms.txt](https://docs.nestjstools.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.nestjstools.com/components/exception-listeners.md).

# 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.

{% hint style="warning" %}
This feature **does not** **work** for an **in-memory** channel
{% endhint %}

***

### 🔍 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:

```ts
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              |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.nestjstools.com/components/exception-listeners.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
