Error Classify And Map
Classify errors by type and map to appropriate HTTP status codes with retry decisions for API layers.
Code
export class AppError extends Error{constructor(message:string,public statusCode:number=500,public isRetryable:boolean=false){super(message);this.name='AppError';}}export class ValidationError extends AppError{constructor(message:string){super(message,400,false);this.name='ValidationError';}}export class NotFoundError extends AppError{constructor(message:string){super(message,404,false);this.name='NotFoundError';}}export function classifyError(e:unknown):AppError{if(e instanceof AppError)return e;if(e instanceof TypeError)return new AppError('type error',400,false);return new AppError('internal error',500,true);}export function shouldRetry(e:unknown):boolean{return classifyError(e).isRetryable;}How the snippet works
The working surface is the classes AppError, ValidationError and NotFoundError and the functions classifyError and shouldRetry — everything else is wiring.
What comes back is a new object, not a reference to anything passed in.
Points of care
- The guard
e instanceof AppErrorshort-circuits the flow with an earlyreturnwhen its condition holds.
Applying it
Import AppError from the file and call it — the rest of the code is implementation detail.
Interactive Tools for This Topic
FAQ
- Does `AppError` modify its input?
- No. Nothing passed in is written to, which makes the call safe on shared data.
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `classifyError`, `shouldRetry` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.