Nestgram v2.0
Docs/The Nest pipeline

Handling errors

Errors arrive from two directions, and Nestgram keeps them apart.

One is the handler side — you want to bail out of a request and tell the user why. Nest’s idiom is throw new HttpException(...); Nestgram’s is throw new ReplyException(...), caught by a global @Catch filter and turned into a reply.

The other is the send side — Telegram rejects an outbound call (ok: false), and Nestgram throws an ApiException carrying the error_code, description, any parameters (like retry_after), and the request body. That one you catch where you made the call, and branch on with typed predicates.

Mental model
throw ReplyException→filter→reply | Telegram rejects→ApiException→predicate

Replying by throwing: ReplyException

Throw a ReplyException anywhere in the pipeline — a guard, a pipe, an interceptor, or the handler — and the request stops there with a reply. No return, no threading a “denied” flag back to the handler. The mover is ReplyExceptionFilter, a global @Catch(ReplyExceptionBase) filter NestgramModule registers as an APP_FILTER. It consumes the exception, so the dispatcher sees a clean completion — no error log.

A guard is the natural home: deny and explain in one throw, instead of returning false (which is silent) and explaining somewhere else.

admin.guard.ts
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common';
import { ReplyException, TelegramExecutionContext } from 'nestgram';

const ADMIN_IDS = [42, 1337];

@Injectable()
export class AdminGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const { from } = TelegramExecutionContext.of(context);
    if (from && ADMIN_IDS.includes(from.id)) {
      return true;
    }
    throw new ReplyException('Only admins can do that.');
  }
}

The handler never runs; the user gets the message. The same throw works for handler-level validation — guard clauses read top-to-bottom instead of nesting:

rename.router.ts
import { Router, Command, Message, ReplyException } from 'nestgram';

@Router()
export class RenameRouter {
  @Command('rename')
  rename(message: Message): string {
    const name = message.text?.split(' ').slice(1).join(' ').trim();
    if (!name) {
      throw new ReplyException('Usage: /rename <new name>');
    }
    return `Renamed to ${name}.`;
  }
}

Internally the filter hands ReplyException.content straight to ResultHandler — the same component that runs a handler’s return value — so the reply mirrors a returned value exactly: a string replies to the same chat, and a command object goes out as-is. Pass reply options after the text, or hand it a ready-made command:

import { ReplyException, SendMessage } from 'nestgram';

// Text with reply options (a keyboard, a reply target…):
throw new ReplyException('Pick one:', { reply_markup: keyboard });

// A full command object — the layer beneath `message.answer(...)`:
throw new ReplyException(new SendMessage({ chat_id, text: 'Done.' }));

Answering a callback query

For a button tap, the right reaction is a toast or modal alert, not a chat message. AnswerException answers the originating callback query — it extends the same ReplyExceptionBase, so the one filter catches it too:

import { AnswerException } from 'nestgram';

// A toast on the button:
throw new AnswerException('Too fast — slow down.');

// A modal alert:
throw new AnswerException('Not allowed', { show_alert: true });

The filter reads ctx.kind to find the callback. Thrown on a non-callback update there’s nothing to answer, so it logs a warning and does nothing.

Sharing a service with HTTP

ReplyException lives on the Telegram layer — throw it from a handler, guard, or interceptor, just as you’d throw HttpException from a controller. Don’t throw it from a domain service you also call over HTTP: that service shouldn’t know the shape of a Telegram reply.

Instead, throw a plain domain error and let each transport map it. It’s one @Catch filter per transport, not one per error — and because the filter holds the context, it picks the right reaction by update kind:

telegram-error.filter.ts
import { ArgumentsHost, Catch, ExceptionFilter } from '@nestjs/common';
import {
  CallbackQuery,
  Message,
  t,
  TelegramExecutionContext,
  UpdateKind,
} from 'nestgram';

// Domain layer — transport-agnostic, reused over HTTP and Telegram. Carries a
// stable `code` and structured fields for rendering, never the user-facing copy:
export abstract class AppError extends Error {
  abstract readonly code: string;
  readonly params: Record<string, string | number> = {};
}
export class InsufficientFundsError extends AppError {
  readonly code = 'insufficient_funds';
  readonly params: Record<string, string | number>;
  constructor(readonly shortBy: number) {
    super(`short by ${shortBy}`); // developer-facing — logs, not the user
    this.params = { shortBy };
  }
}

// Telegram adapter — ONE filter for the whole AppError family. The user-facing
// copy is rendered here from the `code` (a translation key), so the reply is
// localized and the domain stays oblivious to it:
@Catch(AppError)
export class TelegramErrorFilter implements ExceptionFilter {
  async catch(error: AppError, host: ArgumentsHost): Promise<void> {
    const ctx = TelegramExecutionContext.of(host);
    const text = t(`errors.${error.code}`, error.params);
    // Branch by update kind — this transport's own concern, not the domain's:
    if (ctx.kind === UpdateKind.CallbackQuery) {
      await (ctx.event as CallbackQuery).alert(text);
    } else {
      await (ctx.event as Message).answer(text);
    }
  }
}

The HTTP side registers its own @Catch(AppError) filter mapping the same error to, say, a 409 and a JSON body — the service stays oblivious to both.

The trade-off is fundamental, and you pick per case: a ReplyException knows its presentation (zero filters, but Telegram-coupled), a domain error doesn’t (reusable across transports, at the cost of one filter). A Telegram-only bot wants ReplyException and no filters at all.

When the service already throws HttpException

Plenty of existing apps have no neutral domain error — the service throws Nest’s HTTP shortcuts directly (throw new NotFoundException(...), ForbiddenException, …). You don’t have to refactor them to bolt on a bot. An HttpException already carries a transport-neutral discriminator — its status code — so one filter maps the whole family to a reply, and the HTTP app stays untouched:

telegram-http.filter.ts
import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import {
  CallbackQuery,
  Message,
  t,
  TelegramExecutionContext,
  UpdateKind,
} from 'nestgram';

// The HTTP status is the shared semantic code — key localized copy off it,
// with a catch-all, so the service is never touched:
const KEY_BY_STATUS: Partial<Record<number, string>> = {
  [HttpStatus.FORBIDDEN]: 'forbidden',
  [HttpStatus.NOT_FOUND]: 'not_found',
  [HttpStatus.CONFLICT]: 'conflict',
};

@Catch(HttpException)
export class TelegramHttpExceptionFilter implements ExceptionFilter {
  async catch(error: HttpException, host: ArgumentsHost): Promise<void> {
    const ctx = TelegramExecutionContext.of(host);
    const text = t(`errors.${KEY_BY_STATUS[error.getStatus()] ?? 'unknown'}`);
    if (ctx.kind === UpdateKind.CallbackQuery) {
      await (ctx.event as CallbackQuery).alert(text);
    } else {
      await (ctx.event as Message).answer(text);
    }
  }
}

Apply it to the Telegram side only — on your routers, via @UseFilters:

import { Router } from 'nestgram';
import { UseFilters } from '@nestjs/common';

@Router()
@UseFilters(TelegramHttpExceptionFilter)
export class SupportRouter {
  /* … */
}

It’s a pragmatic bridge, not a hack: the status code genuinely encodes the semantic, so reusing it across transports is honest. That the service throws HttpException at all is still a transport leak — the cleaner endgame is the plain domain error above, mapped per transport. Migrate when you can; until then, one filter attaches the bot without touching a line of the existing app.

It pairs naturally with rate limiting: an onLimit callback can throw new ReplyException('Slow down.') to warn the flooder instead of dropping their update silently.

To turn the built-in off — and let ReplyException/AnswerException propagate like any other error — set replyExceptions: false on NestgramModule.forRoot. The filter self-disables by re-throwing, so the exception flows to the dispatcher’s normal logging path, exactly as if the feature didn’t exist:

app.module.ts
import { Module } from '@nestjs/common';
import { NestgramModule } from 'nestgram';

@Module({
  imports: [
    NestgramModule.forRoot({
      token: process.env.BOT_TOKEN ?? '',
      replyExceptions: false,
    }),
  ],
})
export class AppModule {}

The problem with description

That’s the handler side handled. The send side — ApiException — needs its own treatment, because Telegram ships no structured error catalog. Many distinct failures share one error_code (400 alone covers dozens), and the only thing that tells them apart is the human-readable description, whose exact wording Telegram controls and the API spec doesn’t model. Matching it by hand is brittle:

import { ApiException } from 'nestgram';

// Don't: the phrase is Telegram's to change, and this repeats in every bot.
if (error instanceof ApiException && error.description.includes('not modified')) {
}

Typed predicates

ApiException carries static type-guards for the failures every bot meets. Each calls ApiException.matches against a KnownApiError catalog entry — a (code, description-pattern) pair — and narrows unknown to ApiException, so the caught error stays typed and the phrasing lives once, in the framework, not in your code:

broadcast.service.ts
import { ApiException, BotService } from 'nestgram';

async function notify(bot: BotService, chatId: number, text: string) {
  try {
    await bot.sendMessage(chatId, text);
  } catch (error) {
    if (ApiException.isBlockedByUser(error)) {
      // They blocked the bot — a send here can never succeed again.
      await pauseSubscription(chatId);
      return;
    }
    throw error; // anything else is a real failure — let it surface
  }
}

The built-in predicates:

PredicateMatches
ApiException.isNotModified(e)400 · an edit with identical content (a no-op)
ApiException.isNotEditable(e)400 · the message can’t be edited — too old, deleted, or not the bot’s own
ApiException.isChatNotFound(e)400 · the target chat doesn’t exist
ApiException.isBlockedByUser(e)403 · the user blocked the bot

The generic escape hatch

For a code or phrasing not in the table, is(error, code, pattern?) matches an error_code, optionally narrowed by a description pattern you supply:

import { ApiException } from 'nestgram';

if (ApiException.is(error, 403)) {
  // any forbidden — blocked, kicked, deactivated…
}
if (ApiException.is(error, 400, /not enough rights/i)) {
  // a specific 400 the catalog doesn't name yet
}

ignoreNotModified: the edit no-op

Tapping a callback button twice re-sends an identical edit, which Telegram rejects with 400 message is not modified. Every bot with inline-button UI hits it, and the fix is always the same — ignore it. Rather than wrap every editText in a try/catch, opt in once:

app.module.ts
import { Module } from '@nestjs/common';
import { NestgramModule } from 'nestgram';

@Module({
  imports: [
    NestgramModule.forRoot({
      token: process.env.BOT_TOKEN ?? '',
      polling: true,
      ignoreNotModified: true,
    }),
  ],
})
export class AppModule {}

With it on, a “not modified” rejection becomes a successful no-op (the edit methods already return Message | true, and you get true). It’s an ordinary opt-in API interceptor — off by default, because silently eating errors is otherwise a footgun.

If you’d rather handle it inline for one call, the predicate is the same hook the interceptor uses:

import { ApiException } from 'nestgram';

try {
  await message.editText(next);
} catch (error) {
  if (ApiException.isNotModified(error)) return; // double-tap, ignore
  throw error;
}