File size: 1,879 Bytes
2d661b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
 * Base error class for the Engram system.
 *
 * All domain-specific errors should extend this class.
 *
 * @module @engram/common/errors/base
 */

/**
 * Base error class for all Engram errors.
 *
 * Provides structured error handling with:
 * - Error codes for programmatic handling
 * - Cause chaining for root cause analysis
 * - Consistent serialization for logging
 *
 * @example
 * ```ts
 * throw new EngramError("Operation failed", "OP_FAILED", originalError);
 * ```
 */
export class EngramError extends Error {
	/**
	 * Error code for programmatic error handling.
	 * Use SCREAMING_SNAKE_CASE (e.g., "GRAPH_QUERY_FAILED").
	 */
	public readonly code: string;

	/**
	 * Original error that caused this error.
	 * Enables error chaining for debugging.
	 */
	public readonly cause?: Error;

	/**
	 * Timestamp when the error was created.
	 */
	public readonly timestamp: number;

	constructor(message: string, code: string, cause?: Error) {
		super(message);
		this.name = "EngramError";
		this.code = code;
		this.cause = cause;
		this.timestamp = Date.now();

		// Maintains proper stack trace for where error was thrown
		if (Error.captureStackTrace) {
			Error.captureStackTrace(this, this.constructor);
		}
	}

	/**
	 * Convert error to a plain object for logging/serialization.
	 */
	toJSON(): Record<string, unknown> {
		return {
			name: this.name,
			message: this.message,
			code: this.code,
			timestamp: this.timestamp,
			stack: this.stack,
			cause: this.cause
				? {
						name: this.cause.name,
						message: this.cause.message,
						stack: this.cause.stack,
					}
				: undefined,
		};
	}

	/**
	 * Create a formatted string representation for logging.
	 */
	toLogString(): string {
		const parts = [`[${this.code}] ${this.message}`];

		if (this.cause) {
			parts.push(`  Caused by: ${this.cause.message}`);
		}

		return parts.join("\n");
	}
}