Exception Filters

Catch and format errors raised during a request, in TypeScript and Python

Exception filters run last in the request pipeline. They catch anything thrown by guards, middleware, interceptors, pipes, or your handler, and turn it into a consistent error response.

Write and apply a filter

Mark the class, implement catch(), and attach it to a handler.

Mark a class with @ExceptionFilter() and implement catch:

import { ExceptionFilter, ExceptionFilterInterface } from '@nitrostack/core';

@ExceptionFilter()
export class HttpExceptionFilter implements ExceptionFilterInterface {
  catch(exception: unknown, context: ExecutionContext): any {
    // Implementation
  }
}

Apply it with @UseFilters:

@Tool({ name: 'risky_operation' })
@UseFilters(GlobalExceptionFilter)
async riskyOperation(input: RiskyInput, ctx: ExecutionContext) {
  // Errors caught and formatted by filter
}

Protocol: async def catch(self, error: Exception, context: ExecutionContext) -> Any.

from nitrostack import use_filters, injectable, ExecutionContext

@injectable()
class HttpExceptionFilter:
    async def catch(self, error: Exception, context: ExecutionContext):
        context.logger.error(f"{type(error).__name__}: {error}")
        return {
            "error": type(error).__name__,
            "message": str(error),
            "tool": context.tool_name,
        }

@use_filters(HttpExceptionFilter)
async def handler(...):
    ...

Scaffold: nitrostack-py generate filter HttpException.

On this page