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.
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.
aiInvestigationasks an AI provider for an outcome;customInvestigationruns 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.
- A value, returned to the caller as if the method had succeeded. It's validated against
resultSchemafirst;allowDirectResultCreation: falseremoves this outcome. - A result tool, which trypatch runs and whose return value it returns. See Tools.
- A custom error from
customErrors, constructed with a parameter the AI supplies. - A fallback outcome, when it has no correct value to offer instead of guessing one. The AI supplies a short
reason, which becomes the error's message:allowCannotDetermine: not enough information to work out the value → TrypatchCannotDetermineErrorallowUncertainResult: a candidate exists, but confidence is too low → TrypatchUncertainResultErrorallowNoApplicableOutcome: none of the configured outcomes fit → TrypatchNoApplicableOutcomeError
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:
- the abort reason of the signal from
getSignal(see Cancellation) - TrypatchFatalError
- a
customErrorsentry withpropagate: true
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:
investigationBehavior: { allowMethodSource: true },- It's the runtime code from
toString(): compiled, possibly minified JavaScript of the decorated method only. - Keep
@trypatchdirectly 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:
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
customErrorsreaches the caller; anything else it throws is logged, and the method rethrows its original error. - It gets a signal that fires on
timeoutMsor the caller's abort; aninvestigatethat ignores it is abandoned.
Return types and decorator dialects
- Decorated methods must return a
Promise(or beasync): the wrapper always returns one, since recovering a value is async. @trypatchworks with standard (stage-3) decorators and TypeScript's legacyexperimentalDecorators(NestJS, TypeORM, ...), with no configuration.- With stage-3 decorators, a method that doesn't return
Promiseof theresultSchematype is a compile error. Legacy decorators can't see the return type, so declare it yourself.