Async Retry With Typed Errors
Retry async operations with typed error classification and exponential backoff for resilient service calls.
Code
export type RetryError=E<{type:'transient';message:string}|{type:'permanent';message:string};export async function retryTyped<T>(fn:()=>Promise<T>,{maxAttempts=3,baseDelay=100,isRetryable=(e:unknown)=>true}={}):Promise<T>{let lastError:unknown;for(let attempt=0;attempt<maxAttempts;attempt++){try{return await fn();}catch(e){lastError=e;if(!isRetryable(e)||attempt===maxAttempts-1)throw e;await new Promise(r=>setTimeout(r,baseDelay*2**attempt));}}throw lastError;}How it works
Structurally, expect the function retryTyped and nothing else.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Applying it
Callers only need retryTyped — everything else stays internal.
Interactive Tools for This Topic
FAQ
- Will the snippet run without installing packages?
- Yes, it runs as-is — nothing outside the built-in APIs is referenced. The file defines `retryTyped` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.