javascript / intermediate
Snippet
Structuring Domain Error Subclasses for Granular Boundary Handling
Creating object-oriented error hierarchies extending JavaScript's base Error allows applications to carry typed domain context (such as transaction IDs and retry metadata). Prototype chaining via Object.setPrototypeOf ensures reliable instanceof evaluations across component boundaries and error recovery helpers.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
export class ApplicationError extends Error {public readonly timestamp: number = Date.now();constructor(message: string, public readonly code: string) {super(message);this.name = this.constructor.name;Object.setPrototypeOf(this, new.target.prototype);}}export class PaymentGatewayTimeoutError extends ApplicationError {constructor(public readonly transactionId: string, public readonly retryAfterMs: number) {super(`Payment gateway timed out for transaction ${transactionId}`, 'ERR_PAYMENT_TIMEOUT');}}export function resolveErrorRecovery(err: unknown): { fallbackUi: string; canRetry: boolean } {if (err instanceof PaymentGatewayTimeoutError) {return { fallbackUi: 'GatewayBusyPrompt', canRetry: err.retryAfterMs < 5000 };}if (err instanceof ApplicationError) {return { fallbackUi: 'GenericDomainErrorBanner', canRetry: false };}return { fallbackUi: 'CriticalCrashScreen', canRetry: false };}
vue
Breakdown
1
export class ApplicationError extends Error {
Declares an abstract base error subclass establishing shared properties like timestamps and domain codes.
2
Object.setPrototypeOf(this, new.target.prototype);
Restores the prototype chain correctly for custom subclasses inheriting from built-in ES Error.
3
export class PaymentGatewayTimeoutError extends ApplicationError {
Extends the domain base error with specific context attributes like transactionId and retry timing.
4
if (err instanceof PaymentGatewayTimeoutError) {
Evaluates typed class instances to select granular, contextual recovery actions in fallback handlers.