Skip to content

How recovery works ​

When a decorated method throws or rejects, @trypatch investigates the failure and returns a value in its place, or rethrows the original error when it can't produce a correct one.

ts
import { z } from 'zod/v4'
import { trypatch } from '@ssandir/trypatch'

export const QuoteSchema = z.object({
    price: z.number().describe('Price in the smallest currency unit, e.g. cents'),
    currency: z.string().describe('ISO 4217 currency code'),
})
export type Quote = z.infer<typeof QuoteSchema>

export class PricingService {
    @trypatch({
        aiInvestigation: {
            resultSchema: QuoteSchema,
            investigationProvider: {
                provider: 'openai',
                apiKey: process.env.OPENAI_API_KEY!,
            },
        },
    })
    async getQuote (productId: string): Promise<Quote> {
        const response = await fetch(`https://pricing.example.com/products/${productId}/quote`)
        if (!response.ok) throw new Error(`Pricing API returned ${response.status}`)
        // Throws if the upstream changes its response shape
        return QuoteSchema.parse(await response.json())
    }
}

The investigation ​

  • trypatch passes the failure to the investigation as an InvestigationContext: the error, the method's name, arguments and source, and the call's timing.
  • aiInvestigation asks an AI provider for an outcome; customInvestigation runs your own handler instead.
  • Options that could never produce an outcome throw when the decorator is applied, not on the first failure.

Outcomes the AI can pick ​

Every outcome comes with an explanation: why the call failed and why the AI picked that outcome.

The explanation is logged at info level, so only with verbosity: 'high', and passed to onAiInvestigationEnd. Redaction placeholders in it are restored, so treat it as sensitive.

When no value is produced ​

Callers get the method's original error, the same failure they'd see without trypatch. That covers fallback outcomes, custom errors without propagate, timeouts, provider failures and failing result tools; trypatch logs why at error level.

Only three errors replace the original:

Showing the AI the method's code ​

allowMethodSource adds the method's code to the prompt, so the AI knows what the call was meant to return:

ts
investigationBehavior: { allowMethodSource: true },
  • It's the runtime code from toString(): compiled, possibly minified JavaScript of the decorated method only.
  • Keep @trypatch directly above the method, or a wrapper from the decorators below it is sent instead.

Custom investigation ​

customInvestigation replaces the AI with your own investigate handler. Its resolved value is returned in place of the error:

ts
import { trypatch } from '@ssandir/trypatch'

class QuoteUnavailableError extends Error {}

export class PricingService {
    @trypatch({
        customInvestigation: {
            investigate: async (ctx, { signal }) => {
                const [productId] = ctx.args as [string]
                const cached = await fetch(`https://pricing-cache.example.com/${productId}`, { signal })
                if (!cached.ok) throw new QuoteUnavailableError(`No cached quote for ${productId}`)
                return await cached.json()
            },
            customErrors: [{ errorConstructor: QuoteUnavailableError }],
        },
    })
    async getQuote (productId: string): Promise<Quote> {
        return await pricingClient.fetchQuote(productId)
    }
}
  • An error from its customErrors reaches the caller; anything else it throws is logged, and the method rethrows its original error.
  • It gets a signal that fires on timeoutMs or the caller's abort; an investigate that ignores it is abandoned.

Return types and decorator dialects ​

  • Decorated methods must return a Promise (or be async): the wrapper always returns one, since recovering a value is async.
  • @trypatch works with standard (stage-3) decorators and TypeScript's legacy experimentalDecorators (NestJS, TypeORM, ...), with no configuration.
  • With stage-3 decorators, a method that doesn't return Promise of the resultSchema type is a compile error. Legacy decorators can't see the return type, so declare it yourself.