/** * Error Handling — Catch and handle different error types. * * Run: npx tsx examples/15-error-handling.ts */ import { Spectrum, ApiError, RateLimitError, ChainNotFoundError, TimeoutError, NetworkError, ValidationError, } from '@spectrumnodes/sdk'; const spectrum = new Spectrum({ api: process.env.SPECTRUM_API!, timeout: 5_000, retries: 2, }); async function main() { // --- ValidationError (client-side, thrown before any request) --- try { const sdk = new Spectrum({ api: 'http://localhost:3001/test/' }); await sdk.core.getBlockHeight(); // no chain, no defaultChain } catch (err) { if (err instanceof ValidationError) { console.log(`ValidationError: ${err.message} (field: ${err.field})`); } } // --- ChainNotFoundError --- try { await spectrum.core.getBlockHeight('nonexistent-chain'); } catch (err) { if (err instanceof ChainNotFoundError) { console.log(`ChainNotFoundError: ${err.message} (chain: ${err.chain})`); } } // --- ApiError (generic server error) --- try { await spectrum.data.getReceipt('ethereum', 'invalid-hash'); } catch (err) { if (err instanceof ApiError) { console.log(`ApiError: ${err.message} (status: ${err.status}, path: ${err.path})`); } } // --- RateLimitError --- // This fires when the server returns 429 try { // Normally triggered by exceeding rate limits // const promises = Array.from({ length: 200 }, () => spectrum.core.getBlockHeight('ethereum')); // await Promise.all(promises); console.log('\nRateLimitError: would fire on 429 response'); console.log(' Has retryAfter (ms) from Retry-After header'); } catch (err) { if (err instanceof RateLimitError) { console.log(`RateLimitError: retry after ${err.retryAfter}ms`); } } // --- TimeoutError --- try { const slowSdk = new Spectrum({ api: 'http://localhost:3001/test/', timeout: 1, retries: 0 }); // 1ms timeout await slowSdk.core.getBlockHeight('ethereum'); } catch (err) { if (err instanceof TimeoutError) { console.log(`\nTimeoutError: ${err.message} (timeout: ${err.timeout}ms)`); } } // --- NetworkError --- try { const badSdk = new Spectrum({ api: 'http://localhost:1/test/', retries: 0 }); await badSdk.core.getBlockHeight('ethereum'); } catch (err) { if (err instanceof NetworkError) { console.log(`NetworkError: ${err.message}`); } } // --- Generic catch-all --- try { await spectrum.core.getBlockHeight('ethereum'); } catch (err) { if (err instanceof ApiError) { // All Spectrum errors extend SpectrumError console.log(`Status: ${err.status}, Path: ${err.path}`); } else { console.log(`Unexpected error: ${err}`); } } } main().catch(console.error);