javascript / expert
Snippet
Polymorphic Custom Error Taxonomy with Cause Chains in Server Interceptors
Combines OOP error inheritance hierarchy with pattern-matching switch control flow (`switch (true)`). Provides robust error handling for Next.js API interceptors by capturing stack traces and standardizing error responses based on polymorphic error types.
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
export class ApplicationError extends Error {constructor(message, options) {super(message, options);this.name = this.constructor.name;Error.captureStackTrace?.(this, this.constructor);}}export class DatabaseTimeoutError extends ApplicationError {}export class AuthorizationFailedError extends ApplicationError {}export function handleRouteException(error) {switch (true) {case error instanceof DatabaseTimeoutError:return { status: 504, code: 'GATEWAY_TIMEOUT', detail: error.message };case error instanceof AuthorizationFailedError:return { status: 403, code: 'FORBIDDEN', detail: error.message };case error instanceof ApplicationError:return { status: 500, code: 'INTERNAL_APP_ERROR', detail: error.message };default:return { status: 500, code: 'UNKNOWN_FAILURE', detail: 'Unhandled system state' };}}
nextjs
Breakdown
1
export class ApplicationError extends Error {
Defines a custom base error class extending native ES Error.
2
Error.captureStackTrace?.(this, this.constructor);
Preserves clean V8 stack traces excluding the constructor frame.
3
export class DatabaseTimeoutError extends ApplicationError {}
Inherits from base ApplicationError creating a distinct domain exception.
4
switch (true) {
Uses expression-matching control flow to evaluate dynamic boolean conditions cleanly.
5
case error instanceof DatabaseTimeoutError:
Matches runtime instances against specific error classes polymorphically.