Skip to content

Commit

Permalink
Merge pull request #7 from bitcoinerlab/normalize-error-throw
Browse files Browse the repository at this point in the history
fix: normalize error handling and update tests
  • Loading branch information
landabaso authored Jun 17, 2024
2 parents 3ed970e + 2c84025 commit 2dc06e5
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 25 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "@bitcoinerlab/explorer",
"description": "Bitcoin Blockchain Explorer: Client Interface featuring Esplora and Electrum Implementations.",
"homepage": "https://github.com/bitcoinerlab/explorer",
"version": "0.2.0",
"version": "0.2.1",
"author": "Jose-Luis Landabaso",
"license": "MIT",
"prettier": "@bitcoinerlab/configs/prettierConfig.json",
Expand Down
48 changes: 27 additions & 21 deletions src/electrum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ const netModule =
const tlsModule =
typeof global !== 'undefined' && global.tls ? global.tls : tls;

function getErrorMsg(error: unknown): string {
if (typeof error === 'string') {
return error;
} else {
return (error as Error).message;
}
}

function defaultElectrumServer(network: Network = networks.bitcoin): {
host: string;
port: number;
Expand Down Expand Up @@ -167,9 +175,8 @@ export class ElectrumExplorer implements Explorer {
);
const header = await this.#client.blockchainHeaders_subscribe();
this.#updateBlockTipHeight(header);
} catch (_error: unknown) {
const error = _error as Error;
throw new Error(`Failed to init Electrum: ${error.message}`);
} catch (error: unknown) {
throw new Error(`Failed to init Electrum: ${getErrorMsg(error)}`);
}

// Ping every minute to keep connection alive. Reconnect on error.
Expand All @@ -181,11 +188,13 @@ export class ElectrumExplorer implements Explorer {
}
try {
await this.#client.server_ping();
} catch (_error: unknown) {
const error = _error as Error;
} catch (error: unknown) {
// Ping failed, stop pinging and reconnect
await this.close();
console.warn('Reconnecting in 0.5s after ping error:', error.message);
console.warn(
'Reconnecting in 0.5s after ping error:',
getErrorMsg(error)
);
await new Promise(resolve => setTimeout(resolve, 500));
await this.connect();
}
Expand Down Expand Up @@ -302,10 +311,11 @@ export class ElectrumExplorer implements Explorer {
*/
client = await this.#getClient();
history = await client.blockchainScripthash_getHistory(scriptHash);
} catch (_error: unknown) {
const error = _error as Error;
} catch (error: unknown) {
throw new Error(
`Failed getting balance & history of ${scriptHash}: ${error.message}`
`Failed getting balance & history of ${scriptHash}: ${getErrorMsg(
error
)}`
);
}
const _txCount = history.filter(tx => tx.height > 0).length;
Expand Down Expand Up @@ -333,9 +343,8 @@ export class ElectrumExplorer implements Explorer {
const client = await this.#getClient();
const fee = await client.blockchainEstimatefee(target);
feeEstimates[target] = 100000 * fee;
} catch (_error: unknown) {
const error = _error as Error;
throw new Error(`Failed to fetch fee estimates: ${error.message}`);
} catch (error: unknown) {
throw new Error(`Failed to fetch fee estimates: ${getErrorMsg(error)}`);
}
}
checkFeeEstimates(feeEstimates);
Expand Down Expand Up @@ -381,12 +390,11 @@ export class ElectrumExplorer implements Explorer {
try {
const client = await this.#getClient();
history = await client.blockchainScripthash_getHistory(scriptHash);
} catch (_error: unknown) {
const error = _error as Error;
} catch (error: unknown) {
throw new Error(
`Failed to fetch transaction history for address/scriptHash "${
scriptHash || address
}": ${error.message}`
}": ${getErrorMsg(error)}`
);
}
if (history.length > this.#maxTxPerScriptPubKey)
Expand Down Expand Up @@ -422,10 +430,9 @@ export class ElectrumExplorer implements Explorer {
try {
const client = await this.#getClient();
return await client.blockchainTransaction_get(txId);
} catch (_error: unknown) {
const error = _error as Error;
} catch (error: unknown) {
throw new Error(
`Failed to fetch transaction tx for "${txId}": ${error.message}`
`Failed to fetch transaction tx for "${txId}": ${getErrorMsg(error)}`
);
}
}
Expand All @@ -449,9 +456,8 @@ export class ElectrumExplorer implements Explorer {
}

return txId;
} catch (_error: unknown) {
const error = _error as Error;
throw new Error(`Failed to broadcast transaction: ${error.message}`);
} catch (error: unknown) {
throw new Error(`Failed to broadcast transaction: ${getErrorMsg(error)}`);
}
}
}
2 changes: 1 addition & 1 deletion src/esplora.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ async function esploraFetch(
if (!response.ok) {
const errorDetails = await response.text();
throw new Error(
`Network request failed! Status code: ${response.status} (${response.statusText}). URL: ${response.url}. Server response: ${errorDetails}`
`Failed request: ${errorDetails}. Status code: ${response.status} (${response.statusText}). URL: ${response.url}.`
);
}
return response;
Expand Down
7 changes: 7 additions & 0 deletions test/explorer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,13 @@ for (const regtestExplorer of regtestExplorers) {
expect(blockStatus?.blockHash).toBe(header.getId());
expect(blockStatus?.blockHeight).toBe(tipHeight);
});
test(`Push errors`, async () => {
await expect(
explorer.push(
'02000000000101a181e1db4f39ca9b14d764373d919bb01bdaa771a39d61bfc45e4c73b33b6bee00000000171600146a166349647f19f776f9f8c4dc8604b36b854ae4ffffffff02a08601000000000017a914a44bb6bc3228487f4a120fd187b13c23a4886cfc878a0035000000000017a91490bb10362943c1dc6bc97bae807525e934fa9a898702483045022100e4b56cf9ea496604d4ecb9898b7b221a3237e6c9eb12bc1473cf6946ac9244390220215e54c0e3d1131088a56caeac2b21099f33317b865affaef22ee6f3b7ea37980121031dd46bf77dd63d55bab8209dd606b16167d8c75a663475cc5abf85deb64a565600000000'
) //Push a problematic tx that has "Missing inputs"
).rejects.toThrow(/bad-txns-inputs-missingorspent/);
});
test('close', async () => {
await explorer.close();
});
Expand Down

0 comments on commit 2dc06e5

Please sign in to comment.