0
# Error Handling
1
2
Structured error system with specific error codes, contextual information, and comprehensive error categories for debugging and error management.
3
4
## Capabilities
5
6
### Core Error System
7
8
Foundation error classes and interfaces.
9
10
```typescript { .api }
11
/**
12
* Main Solana error class with structured error codes
13
*/
14
class SolanaError extends Error {
15
/** Specific error code for programmatic handling */
16
readonly code: SolanaErrorCode;
17
/** Additional context information */
18
readonly context?: ErrorContext;
19
/** Original error that caused this error */
20
readonly cause?: Error;
21
22
constructor(code: SolanaErrorCode, message?: string, options?: {
23
context?: ErrorContext;
24
cause?: Error;
25
});
26
}
27
28
/**
29
* Union type of all possible error codes
30
*/
31
type SolanaErrorCode =
32
| RpcErrorCode
33
| AddressErrorCode
34
| AccountErrorCode
35
| TransactionErrorCode
36
| CryptoErrorCode
37
| CodecErrorCode
38
| SignerErrorCode
39
| InstructionErrorCode;
40
41
/**
42
* Error context for additional debugging information
43
*/
44
interface ErrorContext {
45
/** Human-readable context */
46
[key: string]: unknown;
47
}
48
```
49
50
### RPC Error Codes
51
52
JSON-RPC and network communication errors.
53
54
```typescript { .api }
55
/**
56
* RPC error codes (range: -32768 to -32000, 8100000-8190999)
57
*/
58
type RpcErrorCode =
59
// JSON-RPC standard errors
60
| -32700 // Parse error
61
| -32600 // Invalid request
62
| -32601 // Method not found
63
| -32602 // Invalid params
64
| -32603 // Internal error
65
| -32000 // Server error
66
// Solana RPC specific errors
67
| 8100000 // RPC endpoint not available
68
| 8100001 // RPC request timeout
69
| 8100002 // RPC response parse error
70
| 8100003 // RPC transport error
71
| 8100004 // RPC rate limit exceeded
72
| 8100005; // RPC invalid response format
73
74
/**
75
* Check if error is an RPC error
76
* @param error - Error to check
77
* @returns True if error is RPC-related
78
*/
79
function isRpcError(error: unknown): error is SolanaError & { code: RpcErrorCode };
80
```
81
82
### Address Error Codes
83
84
Address validation and derivation errors.
85
86
```typescript { .api }
87
/**
88
* Address error codes (range: 2800000-2800999)
89
*/
90
type AddressErrorCode =
91
| 2800000 // Invalid address format
92
| 2800001 // Address decode failed
93
| 2800002 // PDA derivation failed
94
| 2800003 // Invalid PDA seeds
95
| 2800004 // PDA bump out of range
96
| 2800005 // Address not on curve
97
| 2800006; // Invalid seed length
98
99
/**
100
* Check if error is an address error
101
* @param error - Error to check
102
* @returns True if error is address-related
103
*/
104
function isAddressError(error: unknown): error is SolanaError & { code: AddressErrorCode };
105
```
106
107
### Account Error Codes
108
109
Account fetching, parsing, and validation errors.
110
111
```typescript { .api }
112
/**
113
* Account error codes (range: 3230000-3230999)
114
*/
115
type AccountErrorCode =
116
| 3230000 // Account not found
117
| 3230001 // Account decode failed
118
| 3230002 // Account data invalid
119
| 3230003 // Account size mismatch
120
| 3230004 // Account owner mismatch
121
| 3230005 // Account not executable
122
| 3230006; // Account rent exempt check failed
123
124
/**
125
* Check if error is an account error
126
* @param error - Error to check
127
* @returns True if error is account-related
128
*/
129
function isAccountError(error: unknown): error is SolanaError & { code: AccountErrorCode };
130
```
131
132
### Cryptography Error Codes
133
134
Cryptographic operation and key management errors.
135
136
```typescript { .api }
137
/**
138
* Crypto error codes (range: 3610000-3611050)
139
*/
140
type CryptoErrorCode =
141
| 3610000 // SubtleCrypto not available
142
| 3610001 // Key generation failed
143
| 3610002 // Invalid key format
144
| 3610003 // Signature creation failed
145
| 3610004 // Signature verification failed
146
| 3610005 // Key derivation failed
147
| 3610006; // Unsupported crypto operation
148
149
/**
150
* Check if error is a crypto error
151
* @param error - Error to check
152
* @returns True if error is crypto-related
153
*/
154
function isCryptoError(error: unknown): error is SolanaError & { code: CryptoErrorCode };
155
```
156
157
### Transaction Error Codes
158
159
Transaction building, signing, and sending errors.
160
161
```typescript { .api }
162
/**
163
* Transaction error codes (range: 5663000+, 7050000-7050999)
164
*/
165
type TransactionErrorCode =
166
| 5663000 // Transaction build failed
167
| 5663001 // Transaction compile failed
168
| 5663002 // Transaction sign failed
169
| 5663003 // Transaction send failed
170
| 5663004 // Transaction confirmation failed
171
| 7050000 // Blockhash expired
172
| 7050001 // Fee payer insufficient funds
173
| 7050002; // Transaction too large
174
175
/**
176
* Check if error is a transaction error
177
* @param error - Error to check
178
* @returns True if error is transaction-related
179
*/
180
function isTransactionError(error: unknown): error is SolanaError & { code: TransactionErrorCode };
181
```
182
183
### Instruction Error Codes
184
185
Program instruction and execution errors.
186
187
```typescript { .api }
188
/**
189
* Instruction error codes (range: 4128000+, 4615000-4615999)
190
*/
191
type InstructionErrorCode =
192
| 4128000 // Invalid instruction
193
| 4128001 // Instruction data invalid
194
| 4128002 // Insufficient accounts
195
| 4128003 // Account permission denied
196
| 4615000 // Program execution failed
197
| 4615001; // Custom program error
198
199
/**
200
* Check if error is an instruction error
201
* @param error - Error to check
202
* @returns True if error is instruction-related
203
*/
204
function isInstructionError(error: unknown): error is SolanaError & { code: InstructionErrorCode };
205
```
206
207
### Signer Error Codes
208
209
Signing workflow and validation errors.
210
211
```typescript { .api }
212
/**
213
* Signer error codes (range: 5508000-5508999)
214
*/
215
type SignerErrorCode =
216
| 5508000 // Signer not found
217
| 5508001 // Insufficient signers
218
| 5508002 // Invalid signer
219
| 5508003 // Signing failed
220
| 5508004 // Multi-sig validation failed
221
| 5508005; // Signer permission denied
222
223
/**
224
* Check if error is a signer error
225
* @param error - Error to check
226
* @returns True if error is signer-related
227
*/
228
function isSignerError(error: unknown): error is SolanaError & { code: SignerErrorCode };
229
```
230
231
### Codec Error Codes
232
233
Encoding and decoding errors.
234
235
```typescript { .api }
236
/**
237
* Codec error codes (range: 8078000-8078999)
238
*/
239
type CodecErrorCode =
240
| 8078000 // Encode failed
241
| 8078001 // Decode failed
242
| 8078002 // Invalid data format
243
| 8078003 // Data size mismatch
244
| 8078004 // Unsupported encoding
245
| 8078005; // Codec not found
246
247
/**
248
* Check if error is a codec error
249
* @param error - Error to check
250
* @returns True if error is codec-related
251
*/
252
function isCodecError(error: unknown): error is SolanaError & { code: CodecErrorCode };
253
```
254
255
### Error Creation and Utilities
256
257
Create and work with Solana errors.
258
259
```typescript { .api }
260
/**
261
* Create a Solana error with specific code
262
* @param code - Error code
263
* @param message - Error message
264
* @param context - Additional context
265
* @returns New SolanaError instance
266
*/
267
function createSolanaError(
268
code: SolanaErrorCode,
269
message?: string,
270
context?: ErrorContext
271
): SolanaError;
272
273
/**
274
* Wrap an existing error as SolanaError
275
* @param error - Original error
276
* @param code - Solana error code
277
* @param context - Additional context
278
* @returns Wrapped SolanaError
279
*/
280
function wrapError(
281
error: Error,
282
code: SolanaErrorCode,
283
context?: ErrorContext
284
): SolanaError;
285
286
/**
287
* Check if error is a SolanaError
288
* @param error - Error to check
289
* @returns True if error is SolanaError
290
*/
291
function isSolanaError(error: unknown): error is SolanaError;
292
293
/**
294
* Get error category from error code
295
* @param code - Error code
296
* @returns Error category string
297
*/
298
function getErrorCategory(code: SolanaErrorCode): string;
299
300
/**
301
* Get human-readable error description
302
* @param code - Error code
303
* @returns Error description
304
*/
305
function getErrorDescription(code: SolanaErrorCode): string;
306
```
307
308
**Usage Examples:**
309
310
```typescript
311
import {
312
SolanaError,
313
createSolanaError,
314
isRpcError,
315
isAddressError,
316
wrapError
317
} from "@solana/web3.js";
318
319
// Create specific error
320
const rpcError = createSolanaError(
321
8100001, // RPC timeout
322
"RPC request timed out after 30 seconds",
323
{
324
endpoint: "https://api.devnet.solana.com",
325
method: "getAccountInfo",
326
timeout: 30000
327
}
328
);
329
330
// Handle different error types
331
try {
332
await someOperation();
333
} catch (error) {
334
if (isRpcError(error)) {
335
console.error("RPC error:", error.message);
336
console.error("Endpoint:", error.context?.endpoint);
337
} else if (isAddressError(error)) {
338
console.error("Address error:", error.message);
339
} else {
340
console.error("Unknown error:", error);
341
}
342
}
343
344
// Wrap existing errors
345
try {
346
JSON.parse(invalidJson);
347
} catch (error) {
348
throw wrapError(
349
error as Error,
350
8100002, // RPC response parse error
351
{ data: invalidJson }
352
);
353
}
354
```
355
356
### Error Recovery and Retry
357
358
Utilities for error recovery and retry logic.
359
360
```typescript { .api }
361
/**
362
* Retry configuration
363
*/
364
interface RetryConfig {
365
/** Maximum number of retries */
366
maxRetries: number;
367
/** Base delay in milliseconds */
368
baseDelay: number;
369
/** Exponential backoff multiplier */
370
backoffMultiplier?: number;
371
/** Maximum delay in milliseconds */
372
maxDelay?: number;
373
/** Error codes that should trigger retry */
374
retryableErrors?: SolanaErrorCode[];
375
}
376
377
/**
378
* Check if error is retryable
379
* @param error - Error to check
380
* @param retryableErrors - Error codes that can be retried
381
* @returns True if error can be retried
382
*/
383
function isRetryableError(
384
error: unknown,
385
retryableErrors?: SolanaErrorCode[]
386
): boolean;
387
388
/**
389
* Execute function with retry logic
390
* @param fn - Function to execute
391
* @param config - Retry configuration
392
* @returns Promise resolving to function result
393
*/
394
function withRetry<T>(
395
fn: () => Promise<T>,
396
config: RetryConfig
397
): Promise<T>;
398
399
/**
400
* Create error handler with logging
401
* @param logger - Logging function
402
* @returns Error handler function
403
*/
404
function createErrorHandler(
405
logger?: (error: SolanaError) => void
406
): (error: unknown) => never;
407
```
408
409
### Error Logging and Debugging
410
411
Enhanced error information for debugging.
412
413
```typescript { .api }
414
/**
415
* Extract stack trace from error
416
* @param error - Error to analyze
417
* @returns Stack trace information
418
*/
419
function getErrorStackTrace(error: Error): {
420
stack: string[];
421
source?: string;
422
line?: number;
423
column?: number;
424
};
425
426
/**
427
* Format error for logging
428
* @param error - Error to format
429
* @param includeContext - Whether to include context
430
* @returns Formatted error string
431
*/
432
function formatError(error: SolanaError, includeContext?: boolean): string;
433
434
/**
435
* Create error with enhanced debugging info
436
* @param code - Error code
437
* @param message - Error message
438
* @param options - Error options
439
* @returns Enhanced error with debugging info
440
*/
441
function createDebugError(
442
code: SolanaErrorCode,
443
message: string,
444
options?: {
445
context?: ErrorContext;
446
cause?: Error;
447
captureStackTrace?: boolean;
448
}
449
): SolanaError;
450
```
451
452
**Advanced Usage Examples:**
453
454
```typescript
455
import {
456
withRetry,
457
isRetryableError,
458
createErrorHandler,
459
formatError
460
} from "@solana/web3.js";
461
462
// Retry RPC calls with exponential backoff
463
const retryConfig = {
464
maxRetries: 3,
465
baseDelay: 1000,
466
backoffMultiplier: 2,
467
maxDelay: 10000,
468
retryableErrors: [8100001, 8100003, 8100004] // Timeout, transport, rate limit
469
};
470
471
const accountInfo = await withRetry(async () => {
472
return await rpc.getAccountInfo(address).send();
473
}, retryConfig);
474
475
// Global error handler
476
const handleError = createErrorHandler((error) => {
477
console.error("Solana Error:", formatError(error, true));
478
});
479
480
try {
481
await riskyOperation();
482
} catch (error) {
483
handleError(error);
484
}
485
486
// Check if specific operation should be retried
487
if (isRetryableError(error, [8100001, 8100003])) {
488
console.log("Retrying operation...");
489
await delay(1000);
490
await retryOperation();
491
}
492
```