From b10fef9e7d620bdddaff1e832e739c4b7a894910 Mon Sep 17 00:00:00 2001 From: Youngone Lee Date: Tue, 28 Sep 2021 10:25:55 -0500 Subject: [PATCH] build(deps): upgrade to typescript v4.4 Fixes #1129 Signed-off-by: Youngone Lee --- .../typescript/carbon-accounting-app-cli.ts | 20 +- ...bon-accounting-app-dummy-infrastructure.ts | 47 +- .../admin-enroll-v1-endpoint.test.ts | 31 +- .../typescript/src/index.ts | 216 ++++++-- .../src/lib/utilityEmissionsFactor.ts | 17 +- .../typescript/src/util/worldstate.ts | 15 +- .../dao-token/get-allowance-endpoint.ts | 11 +- .../enroll-admin-v1-endpoint.ts | 11 +- .../supply-chain-app-dummy-infrastructure.ts | 47 +- .../main/typescript/supply-chain-app-cli.ts | 19 +- .../insert-bamboo-harvest-endpoint.ts | 11 +- .../web-services/insert-bookshelf-endpoint.ts | 11 +- .../web-services/insert-shipment-endpoint.ts | 11 +- .../list-bamboo-harvest-endpoint.ts | 12 +- .../web-services/list-bookshelf-endpoint.ts | 11 +- .../web-services/list-shipment-endpoint.ts | 11 +- examples/cartrade/asset.ts | 60 ++- .../counterparty-htlc-endpoint.ts | 17 +- .../web-services/own-htlc-endpoint.ts | 17 +- .../withdraw-counterparty-endpoint.ts | 17 +- .../plugin-htlc-coordinator/refund.test.ts | 22 +- .../typescript/plugin-object-store-ipfs.ts | 39 +- .../web-services/get-object-endpoint-v1.ts | 11 +- .../web-services/has-object-endpoint-v1.ts | 11 +- .../web-services/set-object-endpoint-v1.ts | 11 +- package.json | 4 +- .../typescript/default-consortium-provider.ts | 20 +- .../default-consortium-provider.test.ts | 63 ++- .../src/main/typescript/api-server.ts | 84 ++- .../src/main/typescript/cmd/cactus-api.ts | 17 +- .../main/typescript/config/config-service.ts | 15 +- .../watch-healthcheck-v1-endpoint.ts | 11 +- .../web-services/deploy-contract-endpoint.ts | 17 +- .../web-services/run-transaction-endpoint.ts | 17 +- .../unprotected-action-endpoint.ts | 17 +- .../jwt-endpoint-authorization.test.ts | 19 +- ...t-endpoint-authz-scope-enforcement.test.ts | 53 +- ...wt-socketio-endpoint-authorization.test.ts | 19 +- ...otected-endpoint-authz-ops-confirm.test.ts | 16 +- .../jwt-unprotected-endpoint-authz.test.ts | 18 +- .../src/main/typescript/servers.ts | 18 +- .../typescript/unit/js-object-signer.test.ts | 4 +- .../typescript/unit/logging/logger.test.ts | 16 +- .../register-web-service-endpoint.ts | 17 +- .../get-consortium-jws-endpoint-v1.ts | 14 +- .../consortium/get-node-jws-endpoint-v1.ts | 14 +- ...prometheus-exporter-metrics-endpoint-v1.ts | 14 +- .../get-single-status-endpoint.ts | 17 +- .../web-services/get-status-endpoint.ts | 18 +- .../web-services/initialize-endpoint.ts | 17 +- .../web-services/new-contract-endpoint.ts | 18 +- .../web-services/refund-endpoint.ts | 17 +- .../web-services/withdraw-endpoint.ts | 17 +- .../get-single-status-endpoint.ts | 17 +- .../web-services/get-status-endpoint.ts | 17 +- .../web-services/initialize-endpoint.ts | 17 +- .../web-services/new-contract-endpoint.ts | 18 +- .../web-services/refund-endpoint.ts | 17 +- .../web-services/withdraw-endpoint.ts | 17 +- .../main/typescript/plugin-keychain-aws-sm.ts | 85 ++- .../delete-keychain-entry-endpoint-v1.ts | 18 +- .../get-keychain-entry-endpoint-v1.ts | 12 +- .../has-keychain-entry-endpoint-v1.ts | 17 +- .../set-keychain-entry-endpoint-v1.ts | 17 +- .../plugin-keychain-aws-sm.test.ts | 27 +- .../delete-keychain-entry-endpoint-v1.ts | 17 +- .../get-keychain-entry-endpoint-v1.ts | 9 +- .../has-keychain-entry-endpoint-v1.ts | 17 +- .../set-keychain-entry-endpoint-v1.ts | 17 +- .../openapi/openapi-validation.test.ts | 217 ++++---- .../plugin-keychain-google-sm.test.ts | 37 +- .../delete-keychain-entry-endpoint-v1.ts | 17 +- .../get-keychain-entry-endpoint-v1.ts | 9 +- .../has-keychain-entry-endpoint-v1.ts | 17 +- .../set-keychain-entry-endpoint-v1.ts | 15 +- ...prometheus-exporter-metrics-endpoint-v1.ts | 14 +- .../plugin-keychain-vault-remote-adapter.ts | 15 +- .../main/typescript/plugin-keychain-vault.ts | 51 +- .../delete-keychain-entry-endpoint-v1.ts | 11 +- .../get-keychain-entry-endpoint-v1.ts | 11 +- ...prometheus-exporter-metrics-endpoint-v1.ts | 14 +- .../has-keychain-entry-endpoint-v1.ts | 11 +- .../set-keychain-entry-endpoint-v1.ts | 11 +- .../openapi/openapi-validation.test.ts | 236 +++++---- ...loy-contract-solidity-bytecode-endpoint.ts | 17 +- .../web-services/get-balance-endpoint.ts | 17 +- .../get-besu-record-endpoint-v1.ts | 17 +- .../web-services/get-block-v1-endpoint-.ts | 17 +- .../web-services/get-past-logs-endpoint.ts | 17 +- ...prometheus-exporter-metrics-endpoint-v1.ts | 14 +- .../web-services/get-transaction-endpoint.ts | 17 +- .../web-services/invoke-contract-endpoint.ts | 17 +- .../web-services/run-transaction-endpoint.ts | 17 +- .../sign-transaction-endpoint-v1.ts | 14 +- .../openapi/openapi-validation.test.ts | 496 ++++++++++-------- .../deploy-contract-jars-endpoint.ts | 39 +- ...prometheus-exporter-metrics-endpoint-v1.ts | 14 +- .../invoke-contract-endpoint-v1.ts | 14 +- .../deploy-contract-go-source-endpoint-v1.ts | 14 +- .../deploy-contract-endpoint-v1.ts | 14 +- ...prometheus-exporter-metrics-endpoint-v1.ts | 14 +- ...transaction-receipt-by-txid-endpoint-v1.ts | 14 +- .../plugin-ledger-connector-fabric.ts | 68 ++- .../run-transaction-endpoint-v1.ts | 14 +- .../integration/identity-client.test.ts | 14 +- .../openapi/openapi-validation-go.test.ts | 61 ++- .../openapi/openapi-validation.test.ts | 121 +++-- .../plugin-ledger-connector-iroha.ts | 136 ++--- ...prometheus-exporter-metrics-endpoint-v1.ts | 14 +- .../web-services/run-transaction-endpoint.ts | 27 +- .../openapi/openapi-validation.test.ts | 55 +- .../plugin-ledger-connector-quorum.ts | 21 +- ...-solidity-bytecode-endpoint-json-object.ts | 23 +- ...loy-contract-solidity-bytecode-endpoint.ts | 17 +- ...prometheus-exporter-metrics-endpoint-v1.ts | 14 +- .../invoke-contract-endpoint-json-object.ts | 23 +- .../web-services/invoke-contract-endpoint.ts | 17 +- .../web-services/run-transaction-endpoint.ts | 17 +- .../openapi-validation-no-keychain.test.ts | 125 +++-- .../openapi/openapi-validation.test.ts | 187 ++++--- ...loy-contract-solidity-bytecode-endpoint.ts | 17 +- ...prometheus-exporter-metrics-endpoint-v1.ts | 14 +- .../web-services/invoke-contract-endpoint.ts | 17 +- .../web-services/run-transaction-endpoint.ts | 17 +- .../openapi/openapi-validation.test.ts | 181 ++++--- .../openapi/openapi-validation.test.ts | 61 ++- .../initialize-endpoint.test.ts | 9 +- .../new-contract-endpoint.test.ts | 9 +- .../openapi/openapi-validation.test.ts | 337 +++++++----- .../refund-endpoint.test.ts | 9 +- .../withdraw-endpoint.test.ts | 9 +- ...get-single-status-endpoint-invalid.test.ts | 9 +- .../get-status-endpoint-invalid.test.ts | 9 +- .../initialize-endpoint-invalid.test.ts | 9 +- .../new-contract-endpoint-invalid.test.ts | 7 +- .../openapi/openapi-validation.test.ts | 337 +++++++----- .../refund-endpoint-invalid.test.ts | 9 +- .../withdraw-endpoint-invalid.test.ts | 9 +- .../sign-transaction-endpoint.test.ts | 19 +- .../v21-sign-transaction-endpoint.test.ts | 19 +- .../typescript/besu/besu-mp-test-ledger.ts | 16 +- .../main/typescript/besu/besu-test-ledger.ts | 15 +- .../cactus-keychain-vault-server.ts | 15 +- .../src/main/typescript/common/containers.ts | 143 ++++- .../corda-connector-container.ts | 17 +- .../typescript/corda/corda-test-ledger.ts | 30 +- .../fabric/fabric-test-ledger-v1.ts | 76 ++- .../go-ipfs/go-ipfs-test-container.ts | 14 +- .../http-echo/http-echo-container.ts | 15 +- .../typescript/iroha/iroha-test-ledger.ts | 15 +- .../typescript/keycloak/keycloak-container.ts | 15 +- .../localstack/localstack-container.ts | 15 +- .../openethereum/openethereum-test-ledger.ts | 15 +- .../postgres/postgres-test-container.ts | 15 +- .../typescript/quorum/quorum-test-ledger.ts | 33 +- .../rustc-container/rustc-container.ts | 16 +- .../vault-test-server/vault-test-server.ts | 15 +- .../integration/common/containers.test.ts | 21 +- yarn.lock | 121 +++-- 159 files changed, 3824 insertions(+), 1964 deletions(-) diff --git a/examples/cactus-example-carbon-accounting-backend/src/main/typescript/carbon-accounting-app-cli.ts b/examples/cactus-example-carbon-accounting-backend/src/main/typescript/carbon-accounting-app-cli.ts index f2f00b125f2..d681cebeb86 100755 --- a/examples/cactus-example-carbon-accounting-backend/src/main/typescript/carbon-accounting-app-cli.ts +++ b/examples/cactus-example-carbon-accounting-backend/src/main/typescript/carbon-accounting-app-cli.ts @@ -7,6 +7,9 @@ import { CarbonAccountingApp, } from "./carbon-accounting-app"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; + export async function launchApp(): Promise { const configService = new ConfigService(); const config = configService.getOrCreate(); @@ -19,10 +22,19 @@ export async function launchApp(): Promise { const carbonAccountingApp = new CarbonAccountingApp(appOptions); try { await carbonAccountingApp.start(); - } catch (ex) { - console.error(`CarbonAccountingApp crashed. Existing...`, ex); - await carbonAccountingApp?.stop(); - process.exit(-1); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + console.error(`CarbonAccountingApp crashed. Existing...`, ex); + await carbonAccountingApp?.stop(); + process.exit(-1); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } diff --git a/examples/cactus-example-carbon-accounting-backend/src/main/typescript/infrastructure/carbon-accounting-app-dummy-infrastructure.ts b/examples/cactus-example-carbon-accounting-backend/src/main/typescript/infrastructure/carbon-accounting-app-dummy-infrastructure.ts index aa8225d2fdf..5bd42f0f557 100644 --- a/examples/cactus-example-carbon-accounting-backend/src/main/typescript/infrastructure/carbon-accounting-app-dummy-infrastructure.ts +++ b/examples/cactus-example-carbon-accounting-backend/src/main/typescript/infrastructure/carbon-accounting-app-dummy-infrastructure.ts @@ -32,6 +32,8 @@ import { ICarbonAccountingFabricContractDeploymentInfo, ICarbonAccountingXdaiContractDeploymentInfo, } from "@hyperledger/cactus-example-carbon-accounting-business-logic-plugin"; +import { RuntimeError } from "run-time-error"; +import axios from "axios"; export interface ICarbonAccountingAppDummyInfrastructureOptions { logLevel?: LogLevelDesc; @@ -141,9 +143,18 @@ export class CarbonAccountingAppDummyInfrastructure { this.fabric.stop().then(() => this.fabric.destroy()), ]); this.log.info(`Stopped OK`); - } catch (ex) { - this.log.error(`Stopping crashed: `, ex); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`Stopping crashed: `, ex); + throw ex; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } @@ -152,9 +163,18 @@ export class CarbonAccountingAppDummyInfrastructure { this.log.info(`Starting dummy infrastructure...`); await Promise.all([this.xdai.start(), this.fabric.start()]); this.log.info(`Started dummy infrastructure OK`); - } catch (ex) { - this.log.error(`Starting of dummy infrastructure crashed: `, ex); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`Starting of dummy infrastructure crashed: `, ex); + throw ex; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } @@ -361,9 +381,18 @@ export class CarbonAccountingAppDummyInfrastructure { channelName: channelId, }, }; - } catch (ex) { - this.log.error(`Deployment of smart contracts crashed: `, ex); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`Deployment of smart contracts crashed: `, ex); + throw ex; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } diff --git a/examples/cactus-example-carbon-accounting-backend/src/test/typescript/integration/admin-enroll-v1-endpoint.test.ts b/examples/cactus-example-carbon-accounting-backend/src/test/typescript/integration/admin-enroll-v1-endpoint.test.ts index b6837462080..661b10004e1 100644 --- a/examples/cactus-example-carbon-accounting-backend/src/test/typescript/integration/admin-enroll-v1-endpoint.test.ts +++ b/examples/cactus-example-carbon-accounting-backend/src/test/typescript/integration/admin-enroll-v1-endpoint.test.ts @@ -5,6 +5,7 @@ import expressJwt from "express-jwt"; import { v4 as uuidv4 } from "uuid"; import { JWK, JWT } from "jose"; import { StatusCodes } from "http-status-codes"; +import axios from "axios"; import { AuthorizationProtocol, @@ -30,6 +31,7 @@ import { CarbonAccountingApp, ICarbonAccountingAppOptions, } from "../../../main/typescript/carbon-accounting-app"; +import { RuntimeError } from "run-time-error"; const testCase = "can enroll new admin users onto the Fabric org"; const logLevel: LogLevelDesc = "TRACE"; @@ -155,17 +157,24 @@ test(testCase, async (t: Test) => { try { await apiClientBad.enrollAdminV1({ orgName: "does-not-matter" }); t.fail("enroll admin response status === 403 FAIL"); - } catch (out) { - t.ok(out, "error thrown for forbidden endpoint truthy OK"); - t.ok(out.response, "enroll admin response truthy OK"); - t.equal( - out.response.status, - StatusCodes.FORBIDDEN, - "enroll admin response status === 403 OK", - ); - t.notok(out.response.data.data, "out.response.data.data falsy OK"); - t.notok(out.response.data.success, "out.response.data.success falsy OK"); + } catch (out: unknown) { + if (!out) { + const errorMessage = `out is falsy`; + throw new RuntimeError(errorMessage); + } + if (axios.isAxiosError(out)) { + t.ok(out, "error thrown for forbidden endpoint truthy OK"); + t.ok(out.response, "enroll admin response truthy OK"); + t.equal( + out.response?.status, + StatusCodes.FORBIDDEN, + "enroll admin response status === 403 OK", + ); + t.notok(out.response?.data.data, "out.response.data.data falsy OK"); + t.notok(out.response?.data.success, "out.response.data.success falsy OK"); + } else { + t.fail("expected an axios error, got something else"); + } } - t.end(); }); diff --git a/examples/cactus-example-carbon-accounting-backend/src/utility-emissions-channel/typescript/src/index.ts b/examples/cactus-example-carbon-accounting-backend/src/utility-emissions-channel/typescript/src/index.ts index 6052a06de6b..c619b6d674f 100644 --- a/examples/cactus-example-carbon-accounting-backend/src/utility-emissions-channel/typescript/src/index.ts +++ b/examples/cactus-example-carbon-accounting-backend/src/utility-emissions-channel/typescript/src/index.ts @@ -14,6 +14,8 @@ import { MsgSuccess, } from "./util/const"; import { logger, stringToBytes } from "./util/util"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; export class EmissionsChaincode { private methods: { @@ -95,9 +97,18 @@ export class EmissionsChaincode { fieldsMap.url, fieldsMap.md5, ); - } catch (error) { - console.log(error); - return Shim.error(stringToBytes((error as Error).message)); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + console.log(error); + return Shim.error(stringToBytes(error.message)); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected exception", error); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); + } } logger.debug(`${MsgSuccess} recordEmissions success ${byte.toString()}`); return Shim.success(byte); @@ -132,9 +143,18 @@ export class EmissionsChaincode { byte = await new EmissionsRecordContract(stub).updateEmissionsRecord( recordI, ); - } catch (error) { - logger.error(error); - return Shim.error(stringToBytes((error as Error).message)); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + logger.error(error); + return Shim.error(stringToBytes(error.message)); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected exception", error); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); + } } return Shim.success(byte); } @@ -156,9 +176,18 @@ export class EmissionsChaincode { let byte: Uint8Array; try { byte = await new EmissionsRecordContract(stub).getEmissionsData(args[0]); - } catch (error) { - logger.error(error); - return Shim.error(stringToBytes((error as Error).message)); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + logger.error(error); + return Shim.error(stringToBytes(error.message)); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected excpetion", error); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); + } } return Shim.success(byte); } @@ -183,9 +212,18 @@ export class EmissionsChaincode { args[0], args[1], ); - } catch (error) { - logger.error(error); - return Shim.error(stringToBytes((error as Error).message)); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + logger.error(error); + return Shim.error(stringToBytes(error.message)); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected exception", error); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); + } } return Shim.success(byte); } @@ -211,9 +249,18 @@ export class EmissionsChaincode { byte = await new EmissionsRecordContract( stub, ).getAllEmissionsDataByDateRange(args[0], args[1]); - } catch (error) { - logger.error(error); - return Shim.error(stringToBytes((error as Error).message)); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + logger.error(error); + return Shim.error(stringToBytes(error.message)); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected exception", error); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); + } } return Shim.success(byte); } @@ -239,9 +286,18 @@ export class EmissionsChaincode { byte = await new EmissionsRecordContract( stub, ).getAllEmissionsDataByDateRangeAndParty(args[0], args[1], args[2]); - } catch (error) { - logger.error(error); - return Shim.error(stringToBytes((error as Error).message)); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + logger.error(error); + return Shim.error(stringToBytes(error.message)); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected exception", error); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); + } } return Shim.success(byte); } @@ -297,9 +353,18 @@ export class EmissionsChaincode { byte = await new EmissionsRecordContract(stub).importUtilityFactor( factorI, ); - } catch (error) { - logger.error(error); - return Shim.error(stringToBytes((error as Error).message)); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + logger.error(error); + return Shim.error(stringToBytes(error.message)); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected exception", error); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); + } } logger.debug( `${MsgSuccess} importUtilityFactor success ${byte.toString()}`, @@ -358,9 +423,18 @@ export class EmissionsChaincode { byte = await new EmissionsRecordContract(stub).updateUtilityFactor( factorI, ); - } catch (error) { - logger.error(error); - return Shim.error(stringToBytes((error as Error).message)); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + logger.error(error); + return Shim.error(stringToBytes(error.message)); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected exception", error); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); + } } logger.debug( `${MsgSuccess} updateUtilityFactor success ${byte.toString()}`, @@ -389,9 +463,18 @@ export class EmissionsChaincode { let byte: Uint8Array; try { byte = await new EmissionsRecordContract(stub).getUtilityFactor(args[0]); - } catch (error) { - logger.error(error); - return Shim.error(stringToBytes((error as Error).message)); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + logger.error(error); + return Shim.error(stringToBytes(error.message)); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected exception", error); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); + } } return Shim.success(byte); } @@ -434,11 +517,20 @@ export class EmissionsChaincode { let division: DivisionsInterface; try { division = JSON.parse(args[6]) as DivisionsInterface; - } catch (error) { - logger.error( - `${ErrInvalidArgument} : invalid divsion json input ${error}`, - ); - return Shim.error(stringToBytes((error as Error).message)); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + logger.error( + `${ErrInvalidArgument} : invalid divsion json input ${error}`, + ); + return Shim.error(stringToBytes(error.message)); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected exception", error); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); + } } identifier.divisions = division; } @@ -447,9 +539,18 @@ export class EmissionsChaincode { byte = await new EmissionsRecordContract(stub).importUtilityIdentifier( identifier, ); - } catch (error) { - logger.error(error); - return Shim.error(stringToBytes((error as Error).message)); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + logger.error(error); + return Shim.error(stringToBytes(error.message)); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected exception", error); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); + } } logger.debug( `${MsgSuccess} importUtilityIdentifier success ${byte.toString()}`, @@ -516,9 +617,18 @@ export class EmissionsChaincode { byte = await new EmissionsRecordContract(stub).updateUtilityIdentifier( identifier, ); - } catch (error) { - logger.error(error); - return Shim.error(stringToBytes((error as Error).message)); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + logger.error(error); + return Shim.error(stringToBytes(error.message)); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected excpetion", error); + } else { + throw new RuntimeError( + "unexpected with incorrect type", + JSON.stringify(error), + ); + } } logger.debug( `${MsgSuccess} updateUtilityIdentifier success ${byte.toString()}`, @@ -549,9 +659,18 @@ export class EmissionsChaincode { byte = await new EmissionsRecordContract(stub).getUtilityIdentifier( args[0], ); - } catch (error) { - logger.error(error); - return Shim.error(stringToBytes((error as Error).message)); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + logger.error(error); + return Shim.error(stringToBytes(error.message)); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected exception", error); + } else { + throw new RuntimeError( + "unexpected excpetion with incorrect type", + JSON.stringify(error), + ); + } } logger.debug( `${MsgSuccess} getUtilityIdentifier success ${byte.toString()}`, @@ -567,9 +686,18 @@ export class EmissionsChaincode { let byte: Uint8Array; try { byte = await new EmissionsRecordContract(stub).getAllUtilityIdentifiers(); - } catch (error) { - logger.error(error); - return Shim.error(stringToBytes((error as Error).message)); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + logger.error(error); + return Shim.error(stringToBytes(error.message)); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected exception", error); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); + } } return Shim.success(byte); } diff --git a/examples/cactus-example-carbon-accounting-backend/src/utility-emissions-channel/typescript/src/lib/utilityEmissionsFactor.ts b/examples/cactus-example-carbon-accounting-backend/src/utility-emissions-channel/typescript/src/lib/utilityEmissionsFactor.ts index 866265ef3e4..07419a33552 100644 --- a/examples/cactus-example-carbon-accounting-backend/src/utility-emissions-channel/typescript/src/lib/utilityEmissionsFactor.ts +++ b/examples/cactus-example-carbon-accounting-backend/src/utility-emissions-channel/typescript/src/lib/utilityEmissionsFactor.ts @@ -9,11 +9,13 @@ /* tslint:disable:max-classes-per-file */ import { ChaincodeStub } from "fabric-shim"; +import { RuntimeError } from "run-time-error"; import { ErrStateNotFound } from "../util/const"; import { State } from "../util/state"; import { QueryResult, WorldState } from "../util/worldstate"; import { getYearFromDate } from "./emissions-calc"; import { UtilityLookupItemInterface } from "./utilityLookupItem"; +import axios from "axios"; const UTILITY_EMISSIONS_FACTOR_CLASS_IDENTIFIER = "org.hyperledger.blockchain-carbon-accounting.utilityemissionsfactoritem"; @@ -167,9 +169,18 @@ export class UtilityEmissionsFactorState extends WorldState< try { year = getYearFromDate(thruDate); - } catch (error) { - console.error("could not fetch year"); - console.error(error); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + console.error("could not fetch year"); + console.error(error); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected exception", error); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); + } } console.log("fetching utilityFactors"); diff --git a/examples/cactus-example-carbon-accounting-backend/src/utility-emissions-channel/typescript/src/util/worldstate.ts b/examples/cactus-example-carbon-accounting-backend/src/utility-emissions-channel/typescript/src/util/worldstate.ts index 2dd2dc003ce..2a1e3cafd0c 100644 --- a/examples/cactus-example-carbon-accounting-backend/src/utility-emissions-channel/typescript/src/util/worldstate.ts +++ b/examples/cactus-example-carbon-accounting-backend/src/utility-emissions-channel/typescript/src/util/worldstate.ts @@ -9,6 +9,8 @@ import { ErrInvalidQueryString, ErrStateAlreadyExists, } from "./const"; +import { RuntimeError } from "run-time-error"; +import axios from "axios"; /** * WorldState class is a wrapper around chaincode stub * for managing lifecycle of a asset of type T (interface) on HL fabric @@ -64,8 +66,17 @@ export abstract class WorldState extends State { let iterator: Iterators.StateQueryIterator; try { iterator = await this.stub.getQueryResult(queryString); - } catch (error) { - throw new Error(`${ErrInvalidQueryString} : ${(error as Error).message}`); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + throw new Error(`${ErrInvalidQueryString} : ${error.message}`); + } else if (error instanceof Error) { + throw new RuntimeError("unexpected exception", error); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); + } } return await this.getAssetFromIterator(iterator); } diff --git a/examples/cactus-example-carbon-accounting-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/dao-token/get-allowance-endpoint.ts b/examples/cactus-example-carbon-accounting-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/dao-token/get-allowance-endpoint.ts index 9d4c468e641..850bc48f149 100644 --- a/examples/cactus-example-carbon-accounting-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/dao-token/get-allowance-endpoint.ts +++ b/examples/cactus-example-carbon-accounting-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/dao-token/get-allowance-endpoint.ts @@ -81,10 +81,15 @@ export class GetAllowanceEndpoint implements IWebServiceEndpoint { const resBody = await Promise.resolve("dummy-response-fixme"); res.status(200); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.debug(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/examples/cactus-example-carbon-accounting-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/utility-emissions-channel/enroll-admin-v1-endpoint.ts b/examples/cactus-example-carbon-accounting-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/utility-emissions-channel/enroll-admin-v1-endpoint.ts index 7f5bb9dc987..f8dd1e593b7 100644 --- a/examples/cactus-example-carbon-accounting-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/utility-emissions-channel/enroll-admin-v1-endpoint.ts +++ b/examples/cactus-example-carbon-accounting-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/utility-emissions-channel/enroll-admin-v1-endpoint.ts @@ -75,10 +75,15 @@ export class EnrollAdminV1Endpoint implements IWebServiceEndpoint { const resBody = await this.opts.plugin.enrollAdminV1(reqBody); res.status(200); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.debug(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/examples/cactus-example-supply-chain-backend/src/main/typescript/infrastructure/supply-chain-app-dummy-infrastructure.ts b/examples/cactus-example-supply-chain-backend/src/main/typescript/infrastructure/supply-chain-app-dummy-infrastructure.ts index 075d47954db..85b9aac81a0 100644 --- a/examples/cactus-example-supply-chain-backend/src/main/typescript/infrastructure/supply-chain-app-dummy-infrastructure.ts +++ b/examples/cactus-example-supply-chain-backend/src/main/typescript/infrastructure/supply-chain-app-dummy-infrastructure.ts @@ -34,6 +34,8 @@ import { import { DiscoveryOptions } from "fabric-network"; import { SHIPMENT_CONTRACT_GO_SOURCE } from "../../go/shipment"; import { IPluginKeychain } from "@hyperledger/cactus-core-api"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; export const org1Env = { CORE_PEER_LOCALMSPID: "Org1MSP", @@ -142,9 +144,18 @@ export class SupplyChainAppDummyInfrastructure { this.fabric.stop().then(() => this.fabric.destroy()), ]); this.log.info(`Stopped OK`); - } catch (ex) { - this.log.error(`Stopping crashed: `, ex); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`Stopping crashed: `, ex); + throw ex; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } @@ -155,9 +166,18 @@ export class SupplyChainAppDummyInfrastructure { await this.besu.start(); await this.quorum.start(); this.log.info(`Started dummy infrastructure OK`); - } catch (ex) { - this.log.error(`Starting of dummy infrastructure crashed: `, ex); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`Starting of dummy infrastructure crashed: `, ex); + throw ex; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } @@ -332,9 +352,18 @@ export class SupplyChainAppDummyInfrastructure { this.log.info(`Deployed smart contracts OK`); return out; - } catch (ex) { - this.log.error(`Deployment of smart contracts crashed: `, ex); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`Deployment of smart contracts crashed: `, ex); + throw ex; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } } diff --git a/examples/cactus-example-supply-chain-backend/src/main/typescript/supply-chain-app-cli.ts b/examples/cactus-example-supply-chain-backend/src/main/typescript/supply-chain-app-cli.ts index fa0868d4e3a..d169b38145c 100755 --- a/examples/cactus-example-supply-chain-backend/src/main/typescript/supply-chain-app-cli.ts +++ b/examples/cactus-example-supply-chain-backend/src/main/typescript/supply-chain-app-cli.ts @@ -2,6 +2,8 @@ import { ConfigService } from "@hyperledger/cactus-cmd-api-server"; import { LoggerProvider } from "@hyperledger/cactus-common"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; import { ISupplyChainAppOptions, SupplyChainApp } from "./supply-chain-app"; export async function launchApp( @@ -19,10 +21,19 @@ export async function launchApp( const supplyChainApp = new SupplyChainApp(appOptions); try { await supplyChainApp.start(); - } catch (ex) { - console.error(`SupplyChainApp crashed. Existing...`, ex); - await supplyChainApp?.stop(); - process.exit(-1); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + console.error(`SupplyChainApp crashed. Existing...`, ex); + await supplyChainApp?.stop(); + process.exit(-1); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } diff --git a/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/insert-bamboo-harvest-endpoint.ts b/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/insert-bamboo-harvest-endpoint.ts index fb81f9e5e99..331bed144b2 100644 --- a/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/insert-bamboo-harvest-endpoint.ts +++ b/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/insert-bamboo-harvest-endpoint.ts @@ -126,10 +126,15 @@ export class InsertBambooHarvestEndpoint implements IWebServiceEndpoint { const body = { success, callOutput, transactionReceipt }; res.status(200); res.json(body); - } catch (ex) { + } catch (ex: unknown) { this.log.debug(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/insert-bookshelf-endpoint.ts b/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/insert-bookshelf-endpoint.ts index 00bdc60c96c..c1425ba18cc 100644 --- a/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/insert-bookshelf-endpoint.ts +++ b/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/insert-bookshelf-endpoint.ts @@ -114,10 +114,15 @@ export class InsertBookshelfEndpoint implements IWebServiceEndpoint { const body = { callOutput, transactionReceipt }; res.status(200); res.json(body); - } catch (ex) { + } catch (ex: unknown) { this.log.debug(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/insert-shipment-endpoint.ts b/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/insert-shipment-endpoint.ts index 24fe108860e..698e0291913 100644 --- a/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/insert-shipment-endpoint.ts +++ b/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/insert-shipment-endpoint.ts @@ -114,10 +114,15 @@ export class InsertShipmentEndpoint implements IWebServiceEndpoint { res.json(body); res.status(200); - } catch (ex) { + } catch (ex: unknown) { this.log.debug(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/list-bamboo-harvest-endpoint.ts b/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/list-bamboo-harvest-endpoint.ts index 6dd97448d98..0a5acfaa1b9 100644 --- a/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/list-bamboo-harvest-endpoint.ts +++ b/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/list-bamboo-harvest-endpoint.ts @@ -21,7 +21,6 @@ import { import OAS from "../../../json/openapi.json"; import { BambooHarvestConverter } from "../../model/converter/bamboo-harvest-converter"; - export interface IListBambooHarvestEndpointOptions { logLevel?: LogLevelDesc; contractName: string; @@ -116,10 +115,15 @@ export class ListBambooHarvestEndpoint implements IWebServiceEndpoint { const body = { data: rows }; res.status(200); res.json(body); - } catch (ex) { + } catch (ex: unknown) { this.log.debug(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/list-bookshelf-endpoint.ts b/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/list-bookshelf-endpoint.ts index 06d6323c84b..08b6f9306cc 100644 --- a/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/list-bookshelf-endpoint.ts +++ b/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/list-bookshelf-endpoint.ts @@ -114,10 +114,15 @@ export class ListBookshelfEndpoint implements IWebServiceEndpoint { const body = { data: rows }; res.status(200); res.json(body); - } catch (ex) { + } catch (ex: unknown) { this.log.debug(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/list-shipment-endpoint.ts b/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/list-shipment-endpoint.ts index 0a08d7fc8b2..04b9c8c88fe 100644 --- a/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/list-shipment-endpoint.ts +++ b/examples/cactus-example-supply-chain-business-logic-plugin/src/main/typescript/business-logic-plugin/web-services/list-shipment-endpoint.ts @@ -112,10 +112,15 @@ export class ListShipmentEndpoint implements IWebServiceEndpoint { const body = { data: output }; res.status(200); res.json(body); - } catch (ex) { + } catch (ex: unknown) { this.log.debug(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/examples/cartrade/asset.ts b/examples/cartrade/asset.ts index d96c90d53fb..d639a96c797 100644 --- a/examples/cartrade/asset.ts +++ b/examples/cartrade/asset.ts @@ -14,6 +14,8 @@ import { InternalServerError, } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/RIFError"; import { AssetManagement } from "./AssetManagement"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; const fs = require("fs"); const path = require("path"); @@ -38,18 +40,25 @@ router.post("/", (req: Request, res: Response, next: NextFunction) => { .catch((err) => { logger.error(err); }); - } catch (err) { - logger.error(`##err name: ${err.constructor.name}`); - - if (err instanceof RIFError) { - logger.debug(`##catch RIFError, ${err.statusCode}, ${err.message}`); - res.status(err.statusCode); - res.send(err.message); - return; + } catch (err: unknown) { + if (axios.isAxiosError(err)) { + logger.error(`##err name: ${err.constructor.name}`); + if (err instanceof RIFError) { + logger.debug(`##catch RIFError, ${err.statusCode}, ${err.message}`); + res.status(err.statusCode); + res.send(err.message); + return; + } + logger.error(`##err in asset: ${err}`); + next(err); + } else if (err instanceof Error) { + throw new RuntimeError("unexpected exception", err); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(err), + ); } - - logger.error(`##err in asset: ${err}`); - next(err); } }); @@ -65,18 +74,25 @@ router.get("/", (req: Request, res: Response, next: NextFunction) => { .catch((err) => { logger.error(err); }); - } catch (err) { - logger.error(`##err name: ${err.constructor.name}`); - - if (err instanceof RIFError) { - logger.debug(`##catch RIFError, ${err.statusCode}, ${err.message}`); - res.status(err.statusCode); - res.send(err.message); - return; + } catch (err: unknown) { + if (axios.isAxiosError(err)) { + logger.error(`##err name: ${err.constructor.name}`); + if (err instanceof RIFError) { + logger.debug(`##catch RIFError, ${err.statusCode}, ${err.message}`); + res.status(err.statusCode); + res.send(err.message); + return; + } + logger.error(`##err in asset: ${err}`); + next(err); + } else if (err instanceof Error) { + throw new RuntimeError("unexpected exception", err); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(err), + ); } - - logger.error(`##err in asset: ${err}`); - next(err); } }); diff --git a/extensions/cactus-plugin-htlc-coordinator-besu/src/main/typescript/web-services/counterparty-htlc-endpoint.ts b/extensions/cactus-plugin-htlc-coordinator-besu/src/main/typescript/web-services/counterparty-htlc-endpoint.ts index 921ddb067dc..67e199a8635 100644 --- a/extensions/cactus-plugin-htlc-coordinator-besu/src/main/typescript/web-services/counterparty-htlc-endpoint.ts +++ b/extensions/cactus-plugin-htlc-coordinator-besu/src/main/typescript/web-services/counterparty-htlc-endpoint.ts @@ -101,12 +101,19 @@ export class CounterpartyHTLCEndpoint implements IWebServiceEndpoint { }) as unknown) as PluginHTLCCoordinatorBesu; const resBody = await connector.counterpartyHTLC(request); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/extensions/cactus-plugin-htlc-coordinator-besu/src/main/typescript/web-services/own-htlc-endpoint.ts b/extensions/cactus-plugin-htlc-coordinator-besu/src/main/typescript/web-services/own-htlc-endpoint.ts index 621cef9f2a7..d1f813365f7 100644 --- a/extensions/cactus-plugin-htlc-coordinator-besu/src/main/typescript/web-services/own-htlc-endpoint.ts +++ b/extensions/cactus-plugin-htlc-coordinator-besu/src/main/typescript/web-services/own-htlc-endpoint.ts @@ -101,12 +101,19 @@ export class OwnHTLCEndpoint implements IWebServiceEndpoint { }) as unknown) as PluginHTLCCoordinatorBesu; const resBody = await connector.ownHTLC(request); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: ex, + }); + } } } } diff --git a/extensions/cactus-plugin-htlc-coordinator-besu/src/main/typescript/web-services/withdraw-counterparty-endpoint.ts b/extensions/cactus-plugin-htlc-coordinator-besu/src/main/typescript/web-services/withdraw-counterparty-endpoint.ts index 833e8077968..6bc8e145191 100644 --- a/extensions/cactus-plugin-htlc-coordinator-besu/src/main/typescript/web-services/withdraw-counterparty-endpoint.ts +++ b/extensions/cactus-plugin-htlc-coordinator-besu/src/main/typescript/web-services/withdraw-counterparty-endpoint.ts @@ -101,11 +101,18 @@ export class WithdrawCounterpartyEndpoint implements IWebServiceEndpoint { }) as unknown) as PluginHTLCCoordinatorBesu; const resBody = await connector.withdrawCounterparty(request); res.json(resBody); - } catch (ex) { - res.status(500).json({ - message: "Internal Server Error", - error: ex, - }); + } catch (ex: unknown) { + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: ex, + }); + } } } } diff --git a/extensions/cactus-plugin-htlc-coordinator-besu/src/test/typescript/integration/plugin-htlc-coordinator/refund.test.ts b/extensions/cactus-plugin-htlc-coordinator-besu/src/test/typescript/integration/plugin-htlc-coordinator/refund.test.ts index c39d6ac747b..413fdb9bf1d 100644 --- a/extensions/cactus-plugin-htlc-coordinator-besu/src/test/typescript/integration/plugin-htlc-coordinator/refund.test.ts +++ b/extensions/cactus-plugin-htlc-coordinator-besu/src/test/typescript/integration/plugin-htlc-coordinator/refund.test.ts @@ -44,6 +44,9 @@ import HashTimeLockJSON from "@hyperledger/cactus-plugin-htlc-eth-besu-erc20/src import TestTokenJSON from "@hyperledger/cactus-test-plugin-htlc-eth-besu-erc20/src/test/solidity/token-erc20-contract/Test_Token.json"; import DemoHelperJSON from "@hyperledger/cactus-test-plugin-htlc-eth-besu-erc20/src/test/solidity/token-erc20-contract/DemoHelpers.json"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; + const logLevel: LogLevelDesc = "INFO"; const estimatedGas = 6721975; const expiration = 2147483648; @@ -312,11 +315,20 @@ test(testCase, async (t: Test) => { try { await htlcCoordinatorBesuApi.withdrawCounterpartyV1(withdrawCounterparty); - } catch (exp) { - const revertReason = exp.response.data.error.receipt.revertReason; - const regExp = new RegExp(/0e494e56414c49445f5345435245540/); - const rejectMsg = "response === throws OK"; - t.match(revertReason, regExp, rejectMsg); + } catch (exp: unknown) { + if (axios.isAxiosError(exp)) { + const revertReason = exp.response?.data.error.receipt.revertReason; + const regExp = new RegExp(/0e494e56414c49445f5345435245540/); + const rejectMsg = "response === throws OK"; + t.match(revertReason, regExp, rejectMsg); + } else if (exp instanceof Error) { + throw new RuntimeError("unexpected exception", exp); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(exp), + ); + } } t.comment("Get balance of receiver account"); diff --git a/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/plugin-object-store-ipfs.ts b/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/plugin-object-store-ipfs.ts index d28a32d1a17..57e76c427b9 100644 --- a/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/plugin-object-store-ipfs.ts +++ b/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/plugin-object-store-ipfs.ts @@ -24,6 +24,7 @@ import { SetObjectEndpointV1 } from "./web-services/set-object-endpoint-v1"; import { HasObjectEndpointV1 } from "./web-services/has-object-endpoint-v1"; import type { IIpfsHttpClient } from "./i-ipfs-http-client"; import { isIpfsHttpClientOptions } from "./i-ipfs-http-client"; +import axios from "axios"; export const K_IPFS_JS_HTTP_ERROR_FILE_DOES_NOT_EXIST = "HTTPError: file does not exist"; @@ -155,13 +156,25 @@ export class PluginObjectStoreIpfs implements IPluginObjectStore { const statResult = await this.ipfs.files.stat(keyPath); this.log.debug(`StatResult for ${req.key}: %o`, statResult); return { key: req.key, checkedAt, isPresent: true }; - } catch (ex) { - if (ex?.stack?.includes(K_IPFS_JS_HTTP_ERROR_FILE_DOES_NOT_EXIST)) { - const msg = `Stat ${req.key} failed with error message containing phrase "${K_IPFS_JS_HTTP_ERROR_FILE_DOES_NOT_EXIST}" Returning isPresent=false ...`; - this.log.debug(msg); - return { key: req.key, checkedAt, isPresent: false }; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + if (ex.stack?.includes(K_IPFS_JS_HTTP_ERROR_FILE_DOES_NOT_EXIST)) { + const msg = `Stat ${req.key} failed with error message containing phrase "${K_IPFS_JS_HTTP_ERROR_FILE_DOES_NOT_EXIST}" Returning isPresent=false ...`; + this.log.debug(msg); + return { key: req.key, checkedAt, isPresent: false }; + } else { + throw new RuntimeError( + `Checking presence of ${req.key} crashed:`, + ex, + ); + } + } else if (ex instanceof Error) { + throw new RuntimeError(`unexpected exception`, ex); } else { - throw new RuntimeError(`Checking presence of ${req.key} crashed:`, ex); + throw new RuntimeError( + "unexpected exception with incorrect type ", + JSON.stringify(ex), + ); } } } @@ -175,8 +188,18 @@ export class PluginObjectStoreIpfs implements IPluginObjectStore { create: true, parents: true, }); - } catch (ex) { - throw new RuntimeError(`Can't set object ${keyPath}. Write failed:`, ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + throw new RuntimeError( + `Can't set object ${keyPath}. Write failed:`, + ex as Error, + ); + } else { + throw new RuntimeError( + "expected exception with incorrect type", + JSON.stringify(ex), + ); + } } return { key: req.key, diff --git a/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/web-services/get-object-endpoint-v1.ts b/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/web-services/get-object-endpoint-v1.ts index 6003ffef6e7..969c4ae25df 100644 --- a/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/web-services/get-object-endpoint-v1.ts +++ b/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/web-services/get-object-endpoint-v1.ts @@ -91,10 +91,15 @@ export class GetObjectEndpointV1 implements IWebServiceEndpoint { const resBody = await this.plugin.get(reqBody); res.status(200); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/web-services/has-object-endpoint-v1.ts b/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/web-services/has-object-endpoint-v1.ts index c7ba9589303..8fde78634a1 100644 --- a/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/web-services/has-object-endpoint-v1.ts +++ b/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/web-services/has-object-endpoint-v1.ts @@ -91,10 +91,15 @@ export class HasObjectEndpointV1 implements IWebServiceEndpoint { const resBody = await this.plugin.has(reqBody); res.status(200); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/web-services/set-object-endpoint-v1.ts b/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/web-services/set-object-endpoint-v1.ts index 2abae0dd400..159d977c5d7 100644 --- a/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/web-services/set-object-endpoint-v1.ts +++ b/extensions/cactus-plugin-object-store-ipfs/src/main/typescript/web-services/set-object-endpoint-v1.ts @@ -91,10 +91,15 @@ export class SetObjectEndpointV1 implements IWebServiceEndpoint { const resBody = await this.plugin.set(reqBody); res.status(200); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/package.json b/package.json index 7bc29736b67..cade5146e0d 100644 --- a/package.json +++ b/package.json @@ -71,7 +71,7 @@ "devDependencies": { "@commitlint/cli": "13.1.0", "@commitlint/config-conventional": "13.1.0", - "@openapitools/openapi-generator-cli": "2.3.10", + "@openapitools/openapi-generator-cli": "2.4.5", "@types/fs-extra": "9.0.12", "@types/jasminewd2": "2.0.10", "@types/jest": "26.0.24", @@ -131,7 +131,7 @@ "tape-promise": "4.0.0", "ts-loader": "9.2.5", "ts-node": "10.2.0", - "typescript": "4.3.5", + "typescript": "4.4.3", "webpack": "5.50.0", "webpack-bundle-analyzer": "4.4.2", "webpack-cli": "4.7.2" diff --git a/packages/cactus-api-client/src/main/typescript/default-consortium-provider.ts b/packages/cactus-api-client/src/main/typescript/default-consortium-provider.ts index bc2819efd01..266215fe0f6 100644 --- a/packages/cactus-api-client/src/main/typescript/default-consortium-provider.ts +++ b/packages/cactus-api-client/src/main/typescript/default-consortium-provider.ts @@ -12,6 +12,9 @@ import { GetConsortiumJwsResponse, } from "@hyperledger/cactus-plugin-consortium-manual"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; + export interface IDefaultConsortiumProviderOptions { logLevel?: LogLevelDesc; apiClient: ConsortiumManualApi; @@ -63,10 +66,19 @@ export class DefaultConsortiumProvider try { const res = await this.options.apiClient.getConsortiumJwsV1(); return this.parseConsortiumJws(res.data); - } catch (ex) { - const innerException = (ex.toJSON && ex.toJSON()) || ex; - this.log.error(`Request for Consortium JWS failed: `, innerException); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + const innerException = (ex.toJSON && ex.toJSON()) || ex; + this.log.error(`Request for Consortium JWS failed: `, innerException); + throw ex; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } } diff --git a/packages/cactus-api-client/src/test/typescript/integration/default-consortium-provider.test.ts b/packages/cactus-api-client/src/test/typescript/integration/default-consortium-provider.test.ts index ba910ff1342..92677eaa113 100644 --- a/packages/cactus-api-client/src/test/typescript/integration/default-consortium-provider.test.ts +++ b/packages/cactus-api-client/src/test/typescript/integration/default-consortium-provider.test.ts @@ -7,6 +7,9 @@ import { LogLevelDesc, Servers } from "@hyperledger/cactus-common"; import { DefaultConsortiumProvider } from "../../../main/typescript"; import { Configuration } from "@hyperledger/cactus-core-api"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; + test("Reports failures with meaningful information", async (t: Test) => { const logLevel: LogLevelDesc = "TRACE"; @@ -31,15 +34,24 @@ test("Reports failures with meaningful information", async (t: Test) => { try { await provider.get(); t2.fail("Provider.get() did not throw despite API errors."); - } catch (ex) { - t2.ok(ex, "Thrown error truthy OK"); - t2.ok(ex.message, "Thrown error.message truthy OK"); - t2.equal( - typeof ex.message, - "string", - "Thrown error.message type string OK", - ); - t2.true(ex.message.includes("timeout"), "Has timeout in msg OK"); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + t2.ok(ex, "Thrown error truthy OK"); + t2.ok(ex.message, "Thrown error.message truthy OK"); + t2.equal( + typeof ex.message, + "string", + "Thrown error.message type string OK", + ); + t2.true(ex.message.includes("timeout"), "Has timeout in msg OK"); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } t2.end(); }); @@ -56,18 +68,27 @@ test("Reports failures with meaningful information", async (t: Test) => { try { await provider.get(); t2.fail("Provider.get() did not throw despite API errors."); - } catch (ex) { - t2.ok(ex, "Thrown error truthy OK"); - t2.ok(ex.message, "Thrown error.message truthy OK"); - t2.equal( - typeof ex.message, - "string", - "Thrown error.message type string OK", - ); - t2.true( - ex.message.includes("status code 404"), - "Has Status Code in msg OK", - ); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + t2.ok(ex, "Thrown error truthy OK"); + t2.ok(ex.message, "Thrown error.message truthy OK"); + t2.equal( + typeof ex.message, + "string", + "Thrown error.message type string OK", + ); + t2.true( + ex.message.includes("status code 404"), + "Has Status Code in msg OK", + ); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } t2.end(); }); diff --git a/packages/cactus-cmd-api-server/src/main/typescript/api-server.ts b/packages/cactus-cmd-api-server/src/main/typescript/api-server.ts index 935ee798c7c..9ba713358ce 100644 --- a/packages/cactus-cmd-api-server/src/main/typescript/api-server.ts +++ b/packages/cactus-cmd-api-server/src/main/typescript/api-server.ts @@ -56,6 +56,7 @@ import { WatchHealthcheckV1Endpoint } from "./web-services/watch-healthcheck-v1- import * as default_service from "./generated/proto/protoc-gen-ts/services/default_service"; import { GrpcServerApiServer } from "./web-services/grpc/grpc-server-api-server"; import { determineAddressFamily } from "./common/determine-address-family"; +import axios from "axios"; export interface IApiServerConstructorOptions { readonly pluginManagerOptions?: { pluginsPath: string }; @@ -232,17 +233,26 @@ export class ApiServer { } return { addressInfoCockpit, addressInfoApi, addressInfoGrpc }; - } catch (ex) { - const errorMessage = `Failed to start ApiServer: ${ex.stack}`; - this.log.error(errorMessage); - this.log.error(`Attempting shutdown...`); - try { - await this.shutdown(); - this.log.info(`Server shut down after crash OK`); - } catch (ex) { - this.log.error(ApiServer.E_POST_CRASH_SHUTDOWN, ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + const errorMessage = `Failed to start ApiServer: ${ex.stack}`; + this.log.error(errorMessage); + this.log.error(`Attempting shutdown...`); + try { + await this.shutdown(); + this.log.info(`Server shut down after crash OK`); + } catch (ex: unknown) { + this.log.error(ApiServer.E_POST_CRASH_SHUTDOWN, ex); + } + throw new Error(errorMessage); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); } - throw new Error(errorMessage); } } @@ -336,19 +346,21 @@ export class ApiServer { // need to invoke the i-cactus-plugin onPluginInit functionality here before plugin registry can be used further try { await plugin.onPluginInit(); - } catch (error) { - const fnTag = `${this.className}#instantiatePlugin`; - const packageName = plugin.getPackageName(); - const instanceId = plugin.getInstanceId(); - - const errorMessage = `${fnTag} failed calling onPluginInit() on the plugin '${packageName}' with the instanceId '${instanceId}'`; - - this.log.error(errorMessage, error); - + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + const fnTag = `${this.className}#instantiatePlugin`; + const packageName = plugin.getPackageName(); + const instanceId = plugin.getInstanceId(); + const errorMessage = `${fnTag} failed calling onPluginInit() on the plugin '${packageName}' with the instanceId '${instanceId}'`; + this.log.error(errorMessage, error); + } if (error instanceof Error) { - throw new RuntimeError(errorMessage, error); + throw new RuntimeError("unexpected exception", error); } else { - throw new RuntimeError(errorMessage, JSON.stringify(error)); + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(error), + ); } } @@ -370,10 +382,19 @@ export class ApiServer { try { await fs.mkdirp(pluginPackageDir); this.log.debug(`${pkgName} plugin package dir: %o`, pluginPackageDir); - } catch (ex) { - const errorMessage = - "Could not create plugin installation directory, check the file-system permissions."; - throw new RuntimeError(errorMessage, ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + const errorMessage = + "Could not create plugin installation directory, check the file-system permissions."; + throw new RuntimeError(errorMessage, ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } try { lmify.setPackageManager("npm"); @@ -395,8 +416,17 @@ export class ApiServer { throw new RuntimeError("Non-zero exit code: ", JSON.stringify(out)); } this.log.info(`Installed ${pkgName} OK`); - } catch (ex) { - throw new RuntimeError(`${fnTag} plugin install fail: ${pkgName}`, ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + throw new RuntimeError(`${fnTag} plugin install fail: ${pkgName}`, ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } diff --git a/packages/cactus-cmd-api-server/src/main/typescript/cmd/cactus-api.ts b/packages/cactus-cmd-api-server/src/main/typescript/cmd/cactus-api.ts index 27069d338f7..bc4e5a2a1a5 100644 --- a/packages/cactus-cmd-api-server/src/main/typescript/cmd/cactus-api.ts +++ b/packages/cactus-cmd-api-server/src/main/typescript/cmd/cactus-api.ts @@ -3,6 +3,8 @@ import { ApiServer } from "../api-server"; import { ConfigService } from "../config/config-service"; import { Logger, LoggerProvider } from "@hyperledger/cactus-common"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; const log: Logger = LoggerProvider.getOrCreate({ label: "cactus-api", @@ -31,9 +33,18 @@ export async function launchApp(): Promise { try { await main(); log.info(`Cactus API server launched OK `); - } catch (ex) { - log.error(`Cactus API server crashed: `, ex); - process.exit(1); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + log.error(`Cactus API server crashed: `, ex); + process.exit(1); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } diff --git a/packages/cactus-cmd-api-server/src/main/typescript/config/config-service.ts b/packages/cactus-cmd-api-server/src/main/typescript/config/config-service.ts index e4938d2467f..0c7280f7997 100644 --- a/packages/cactus-cmd-api-server/src/main/typescript/config/config-service.ts +++ b/packages/cactus-cmd-api-server/src/main/typescript/config/config-service.ts @@ -21,6 +21,8 @@ import { FORMAT_PLUGIN_ARRAY } from "./convict-plugin-array-format"; import { SelfSignedPkiGenerator, IPki } from "./self-signed-pki-generator"; import { AuthorizationProtocol } from "./authorization-protocol"; import { IAuthorizationConfig } from "../authzn/i-authorization-config"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; convict.addFormat(FORMAT_PLUGIN_ARRAY); convict.addFormat(ipaddress); @@ -636,8 +638,17 @@ export class ConfigService { const jws = JWS.sign({ hello: "world" }, keyPair); try { JWS.verify(jws, keyPair); - } catch (ex) { - throw new Error(`${fnTag} Invalid key pair PEM: ${ex && ex.stack}`); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + throw new Error(`${fnTag} Invalid key pair PEM: ${ex && ex.stack}`); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } } diff --git a/packages/cactus-cmd-api-server/src/main/typescript/web-services/watch-healthcheck-v1-endpoint.ts b/packages/cactus-cmd-api-server/src/main/typescript/web-services/watch-healthcheck-v1-endpoint.ts index c6db12eea01..41f40cce059 100644 --- a/packages/cactus-cmd-api-server/src/main/typescript/web-services/watch-healthcheck-v1-endpoint.ts +++ b/packages/cactus-cmd-api-server/src/main/typescript/web-services/watch-healthcheck-v1-endpoint.ts @@ -51,10 +51,15 @@ export class WatchHealthcheckV1Endpoint { success: true, }; socket.emit(WatchHealthcheckV1.Next, next); - } catch (ex) { + } catch (ex: unknown) { log.error(`Failed to construct health check response:`, ex); - socket.emit(WatchHealthcheckV1.Error, ex); - clearInterval(timerId); + if (ex instanceof Error) { + socket.emit(WatchHealthcheckV1.Error, ex); + clearInterval(timerId); + } else { + socket.emit(WatchHealthcheckV1.Error, new Error(JSON.stringify(ex))); + clearInterval(timerId); + } } }, 1000); diff --git a/packages/cactus-cmd-api-server/src/test/typescript/fixtures/plugin-ledger-connector-stub/web-services/deploy-contract-endpoint.ts b/packages/cactus-cmd-api-server/src/test/typescript/fixtures/plugin-ledger-connector-stub/web-services/deploy-contract-endpoint.ts index a635c6cc8e8..10684ab15a9 100644 --- a/packages/cactus-cmd-api-server/src/test/typescript/fixtures/plugin-ledger-connector-stub/web-services/deploy-contract-endpoint.ts +++ b/packages/cactus-cmd-api-server/src/test/typescript/fixtures/plugin-ledger-connector-stub/web-services/deploy-contract-endpoint.ts @@ -100,12 +100,19 @@ export class DeployContractEndpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.deployContract(reqBody); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-cmd-api-server/src/test/typescript/fixtures/plugin-ledger-connector-stub/web-services/run-transaction-endpoint.ts b/packages/cactus-cmd-api-server/src/test/typescript/fixtures/plugin-ledger-connector-stub/web-services/run-transaction-endpoint.ts index a65646909c3..41200ac6f23 100644 --- a/packages/cactus-cmd-api-server/src/test/typescript/fixtures/plugin-ledger-connector-stub/web-services/run-transaction-endpoint.ts +++ b/packages/cactus-cmd-api-server/src/test/typescript/fixtures/plugin-ledger-connector-stub/web-services/run-transaction-endpoint.ts @@ -98,12 +98,19 @@ export class RunTransactionEndpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.transact(reqBody); res.json({ success: true, data: resBody }); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-cmd-api-server/src/test/typescript/fixtures/plugin-ledger-connector-stub/web-services/unprotected-action-endpoint.ts b/packages/cactus-cmd-api-server/src/test/typescript/fixtures/plugin-ledger-connector-stub/web-services/unprotected-action-endpoint.ts index 7b0b9d6b0bb..62c62cf6928 100644 --- a/packages/cactus-cmd-api-server/src/test/typescript/fixtures/plugin-ledger-connector-stub/web-services/unprotected-action-endpoint.ts +++ b/packages/cactus-cmd-api-server/src/test/typescript/fixtures/plugin-ledger-connector-stub/web-services/unprotected-action-endpoint.ts @@ -104,12 +104,19 @@ export class UnprotectedActionEndpoint implements IWebServiceEndpoint { const somethingPubliclyKnown = "2+2=4"; const data = { reqBody, somethingPublic: somethingPubliclyKnown }; res.json({ success: true, data }); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-endpoint-authorization.test.ts b/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-endpoint-authorization.test.ts index 8d426b95e6b..f6af5780f39 100644 --- a/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-endpoint-authorization.test.ts +++ b/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-endpoint-authorization.test.ts @@ -18,6 +18,8 @@ import { } from "@hyperledger/cactus-core-api"; import { AuthorizationProtocol } from "../../../main/typescript/config/authorization-protocol"; import { IAuthorizationConfig } from "../../../main/typescript/authzn/i-authorization-config"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; const testCase = "API server enforces authorization rules when configured"; const logLevel: LogLevelDesc = "TRACE"; @@ -136,9 +138,18 @@ test(testCase, async (t: Test) => { t.ok(resHc.data.success, "resHc.data.success truthy OK"); t.true(isHealthcheckResponse(resHc.data), "isHealthcheckResponse OK"); t.end(); - } catch (ex) { - log.error(ex); - t.fail("Exception thrown during test execution, see above for details!"); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + log.error(ex); + t.fail("Exception thrown during test execution, see above for details!"); + throw ex; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); diff --git a/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-endpoint-authz-scope-enforcement.test.ts b/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-endpoint-authz-scope-enforcement.test.ts index 1bb8aa70ce8..86ec4b14ac6 100644 --- a/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-endpoint-authz-scope-enforcement.test.ts +++ b/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-endpoint-authz-scope-enforcement.test.ts @@ -19,6 +19,7 @@ import { PluginLedgerConnectorStub } from "../fixtures/plugin-ledger-connector-s import { RunTransactionEndpoint } from "../fixtures/plugin-ledger-connector-stub/web-services/run-transaction-endpoint"; import { DeployContractEndpoint } from "../fixtures/plugin-ledger-connector-stub/web-services/deploy-contract-endpoint"; import { UnprotectedActionEndpoint } from "../fixtures/plugin-ledger-connector-stub/web-services/unprotected-action-endpoint"; +import { RuntimeError } from "run-time-error"; const testCase = "API server enforces scope requirements on top of generic authz"; @@ -141,21 +142,45 @@ test(testCase, async (t: Test) => { }, }); t.fail("deploy contract response status === 403 FAIL"); - } catch (out) { - t.ok(out, "error thrown for forbidden endpoint truthy OK"); - t.ok(out.response, "deploy contract response truthy OK"); - t.equal( - out.response.status, - StatusCodes.FORBIDDEN, - "deploy contract response status === 403 OK", - ); - t.notok(out.response.data.data, "out.response.data.data falsy OK"); - t.notok(out.response.data.success, "out.response.data.success falsy OK"); + } catch (out: unknown) { + if (axios.isAxiosError(out)) { + t.ok(out, "error thrown for forbidden endpoint truthy OK"); + t.ok(out.response, "deploy contract response truthy OK"); + t.equal( + out.response?.status, + StatusCodes.FORBIDDEN, + "deploy contract response status === 403 OK", + ); + t.notok( + out.response?.data.data, + "(out as any).response.data.data falsy OK", + ); + t.notok( + out.response?.data.success, + "(out as any).response.data.success falsy OK", + ); + } else if (out instanceof Error) { + throw new RuntimeError("unexpected exception", out); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(out), + ); + } } t.end(); - } catch (ex) { - log.error(ex); - t.fail("Exception thrown during test execution, see above for details!"); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + log.error(ex); + t.fail("Exception thrown during test execution, see above for details!"); + throw ex; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); diff --git a/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-socketio-endpoint-authorization.test.ts b/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-socketio-endpoint-authorization.test.ts index bbc3dc2c619..90c92df7055 100644 --- a/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-socketio-endpoint-authorization.test.ts +++ b/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-socketio-endpoint-authorization.test.ts @@ -16,6 +16,8 @@ import { ApiServerApiClientConfiguration } from "../../../main/typescript/public import { LoggerProvider, LogLevelDesc } from "@hyperledger/cactus-common"; import { AuthorizationProtocol } from "../../../main/typescript/config/authorization-protocol"; import { IAuthorizationConfig } from "../../../main/typescript/authzn/i-authorization-config"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; const testCase = "API server enforces authorization for SocketIO endpoints"; const logLevel: LogLevelDesc = "TRACE"; @@ -181,9 +183,18 @@ test(testCase, async (t: Test) => { t.true(isHealthcheckResponse(resHc.data), "isHealthcheckResponse OK"); } t.end(); - } catch (ex) { - log.error(ex); - t.fail("Exception thrown during test execution, see above for details!"); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + log.error(ex); + t.fail("Exception thrown during test execution, see above for details!"); + throw ex; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); diff --git a/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-unprotected-endpoint-authz-ops-confirm.test.ts b/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-unprotected-endpoint-authz-ops-confirm.test.ts index bf1ab283d17..0efe174e37c 100644 --- a/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-unprotected-endpoint-authz-ops-confirm.test.ts +++ b/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-unprotected-endpoint-authz-ops-confirm.test.ts @@ -14,6 +14,7 @@ import { } from "../../../main/typescript/public-api"; import { PluginLedgerConnectorStub } from "../fixtures/plugin-ledger-connector-stub/plugin-ledger-connector-stub"; +import axios from "axios"; const testCase = "block unprotected endpoint if not confirmed by ops via deploy-time configuration"; @@ -75,9 +76,16 @@ test(testCase, async (t: Test) => { mainAssertion, ); t.end(); - } catch (ex) { - log.error(ex); - t.fail("Exception thrown during test execution, see above for details!"); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + log.error(ex); + t.fail("Exception thrown during test execution, see above for details!"); + throw ex; + } else { + log.error(ex); + t.fail("Exception thrown during test execution, see above for details!"); + throw ex; + } } + t.end(); }); diff --git a/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-unprotected-endpoint-authz.test.ts b/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-unprotected-endpoint-authz.test.ts index e7cc4259121..3345cb6add6 100644 --- a/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-unprotected-endpoint-authz.test.ts +++ b/packages/cactus-cmd-api-server/src/test/typescript/integration/jwt-unprotected-endpoint-authz.test.ts @@ -17,6 +17,7 @@ import { import { PluginLedgerConnectorStub } from "../fixtures/plugin-ledger-connector-stub/plugin-ledger-connector-stub"; import { UnprotectedActionEndpoint } from "../fixtures/plugin-ledger-connector-stub/web-services/unprotected-action-endpoint"; +import { RuntimeError } from "run-time-error"; const testCase = "API server enforces scope requirements on top of generic authz"; @@ -119,9 +120,18 @@ test(testCase, async (t: Test) => { req1.requestId, "res1.data.requestId === req1.requestId OK", ); - } catch (ex) { - log.error(ex); - t.fail("Exception thrown during test execution, see above for details!"); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + log.error(ex); + t.fail("Exception thrown during test execution, see above for details!"); + throw ex; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); diff --git a/packages/cactus-common/src/main/typescript/servers.ts b/packages/cactus-common/src/main/typescript/servers.ts index 21ba40b4f36..b8059e2fe4b 100644 --- a/packages/cactus-common/src/main/typescript/servers.ts +++ b/packages/cactus-common/src/main/typescript/servers.ts @@ -2,6 +2,8 @@ import { AddressInfo, ListenOptions } from "net"; import { Server, createServer } from "http"; import { Server as SecureServer } from "https"; import { Checks } from "./checks"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; export interface IListenOptions { server: Server | SecureServer; @@ -88,10 +90,18 @@ export class Servers { try { const server = await Servers.startOnPort(preferredPort, host); return server; - } catch (ex) { - // if something else went wrong we still want to just give up - if (!ex.message.includes("EADDRINUSE")) { - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + if (!ex.message.includes("EADDRINUSE")) { + throw ex; + } + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); } } return Servers.startOnPort(0); diff --git a/packages/cactus-common/src/test/typescript/unit/js-object-signer.test.ts b/packages/cactus-common/src/test/typescript/unit/js-object-signer.test.ts index 9c34a559cee..6340169a6ba 100644 --- a/packages/cactus-common/src/test/typescript/unit/js-object-signer.test.ts +++ b/packages/cactus-common/src/test/typescript/unit/js-object-signer.test.ts @@ -211,9 +211,11 @@ test("Test missing required constructor field", async (assert: Test) => { privateKey: pkey as Uint8Array, }; new JsObjectSigner(jsObjectSignerOptions); - } catch (e) { + } catch (e: unknown) { if (e instanceof Error) { assert.equal(e.message, "JsObjectSigner#ctor options.privateKey falsy."); + } else { + assert.fail("expected an axios error, got something else"); } } assert.end(); diff --git a/packages/cactus-common/src/test/typescript/unit/logging/logger.test.ts b/packages/cactus-common/src/test/typescript/unit/logging/logger.test.ts index dff42440a2c..635bd0208fa 100644 --- a/packages/cactus-common/src/test/typescript/unit/logging/logger.test.ts +++ b/packages/cactus-common/src/test/typescript/unit/logging/logger.test.ts @@ -1,7 +1,8 @@ +import { RuntimeError } from "run-time-error"; import test, { Test } from "tape"; import { v4 as uuidv4 } from "uuid"; import { LoggerProvider } from "../../../../main/typescript/public-api"; - +import axios from "axios"; // FIXME(2020-11-12) this does not work because for some reason the stdout // stream does not emit 'data' events with anything even though it should. // Suspecting that the test runner library does some internal magic with @@ -52,8 +53,17 @@ test.skip("Logger#debug/error writes to stdout/stderr", async (t: Test) => { }); didNotThrow = true; - } catch (ex) { - didNotThrow = false; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + didNotThrow = false; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } process.stdout.off("data", stdOutDataHandler as any); diff --git a/packages/cactus-core/src/main/typescript/web-services/register-web-service-endpoint.ts b/packages/cactus-core/src/main/typescript/web-services/register-web-service-endpoint.ts index 5a3c4ad63b1..5919e01dbb2 100644 --- a/packages/cactus-core/src/main/typescript/web-services/register-web-service-endpoint.ts +++ b/packages/cactus-core/src/main/typescript/web-services/register-web-service-endpoint.ts @@ -34,10 +34,17 @@ export async function registerWebServiceEndpoint( } else { registrationMethod(httpPath, requestHandler); } - } catch (ex) { - throw new Error( - `${fnTag} Express verb method ${httpVerb} threw ` + - ` while registering endpoint: ${ex.message}`, - ); + } catch (ex: unknown) { + if (ex instanceof Error) { + throw new Error( + `${fnTag} Express verb method ${httpVerb} threw ` + + ` while registering endpoint: ${ex.message}`, + ); + } else { + throw new Error( + `${fnTag} Express verb method ${httpVerb} threw ` + + ` while registering endpoint: ${JSON.stringify(ex)}`, + ); + } } } diff --git a/packages/cactus-plugin-consortium-manual/src/main/typescript/consortium/get-consortium-jws-endpoint-v1.ts b/packages/cactus-plugin-consortium-manual/src/main/typescript/consortium/get-consortium-jws-endpoint-v1.ts index ce630c1a7d5..cdc90438649 100644 --- a/packages/cactus-plugin-consortium-manual/src/main/typescript/consortium/get-consortium-jws-endpoint-v1.ts +++ b/packages/cactus-plugin-consortium-manual/src/main/typescript/consortium/get-consortium-jws-endpoint-v1.ts @@ -107,11 +107,17 @@ export class GetConsortiumEndpointV1 implements IWebServiceEndpoint { const body: GetConsortiumJwsResponse = { jws }; res.status(200); res.json(body); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-consortium-manual/src/main/typescript/consortium/get-node-jws-endpoint-v1.ts b/packages/cactus-plugin-consortium-manual/src/main/typescript/consortium/get-node-jws-endpoint-v1.ts index 0dc8bb71c18..c0dfc732e17 100644 --- a/packages/cactus-plugin-consortium-manual/src/main/typescript/consortium/get-node-jws-endpoint-v1.ts +++ b/packages/cactus-plugin-consortium-manual/src/main/typescript/consortium/get-node-jws-endpoint-v1.ts @@ -103,11 +103,17 @@ export class GetNodeJwsEndpoint implements IWebServiceEndpoint { const body: GetNodeJwsResponse = { jws }; res.status(200); res.json(body); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-consortium-manual/src/main/typescript/consortium/get-prometheus-exporter-metrics-endpoint-v1.ts b/packages/cactus-plugin-consortium-manual/src/main/typescript/consortium/get-prometheus-exporter-metrics-endpoint-v1.ts index 016a6f81c23..b03cb2bf762 100644 --- a/packages/cactus-plugin-consortium-manual/src/main/typescript/consortium/get-prometheus-exporter-metrics-endpoint-v1.ts +++ b/packages/cactus-plugin-consortium-manual/src/main/typescript/consortium/get-prometheus-exporter-metrics-endpoint-v1.ts @@ -91,11 +91,17 @@ export class GetPrometheusExporterMetricsEndpointV1 const resBody = await this.opts.plugin.getPrometheusExporterMetrics(); res.status(200); res.send(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/get-single-status-endpoint.ts b/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/get-single-status-endpoint.ts index 1840d1cf8b7..7d10f98cbaa 100644 --- a/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/get-single-status-endpoint.ts +++ b/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/get-single-status-endpoint.ts @@ -83,12 +83,19 @@ export class GetSingleStatusEndpoint implements IWebServiceEndpoint { ); res.send(callOutput); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(400).json({ - message: "Bad request", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(400).json({ + message: "Bad request", + error: ex.stack || ex.message, + }); + } else { + res.status(400).json({ + message: "Bad request", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/get-status-endpoint.ts b/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/get-status-endpoint.ts index 562cf298cc4..395717a040e 100644 --- a/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/get-status-endpoint.ts +++ b/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/get-status-endpoint.ts @@ -15,7 +15,6 @@ import { import { registerWebServiceEndpoint } from "@hyperledger/cactus-core"; import OAS from "../../json/openapi.json"; import { PluginHtlcEthBesuErc20 } from "../plugin-htlc-eth-besu-erc20"; - export interface IGetStatusEndpointOptions { logLevel?: LogLevelDesc; plugin: PluginHtlcEthBesuErc20; @@ -83,12 +82,19 @@ export class GetStatusEndpoint implements IWebServiceEndpoint { const { callOutput } = await this.options.plugin.getStatus(req.body); res.send(callOutput); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(400).json({ - message: "Bad request", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(400).json({ + message: "Bad request", + error: ex.stack || ex.message, + }); + } else { + res.status(400).json({ + message: "Bad request", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/initialize-endpoint.ts b/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/initialize-endpoint.ts index d874da9cbb3..da391934784 100644 --- a/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/initialize-endpoint.ts +++ b/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/initialize-endpoint.ts @@ -87,12 +87,19 @@ export class InitializeEndpoint implements IWebServiceEndpoint { const request: InitializeRequest = req.body as InitializeRequest; const result = await this.options.plugin.initialize(request); res.send(result); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(400).json({ - message: "Bad request", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(400).json({ + message: "Bad request", + error: ex.stack || ex.message, + }); + } else { + res.status(400).json({ + message: "Bad request", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/new-contract-endpoint.ts b/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/new-contract-endpoint.ts index ec7a2731bb1..968b1197fde 100644 --- a/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/new-contract-endpoint.ts +++ b/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/new-contract-endpoint.ts @@ -15,7 +15,6 @@ import { registerWebServiceEndpoint } from "@hyperledger/cactus-core"; import { NewContractRequest } from "../generated/openapi/typescript-axios"; import OAS from "../../json/openapi.json"; import { PluginHtlcEthBesuErc20 } from "../plugin-htlc-eth-besu-erc20"; - export interface INewContractEndpointOptions { logLevel?: LogLevelDesc; plugin: PluginHtlcEthBesuErc20; @@ -83,12 +82,19 @@ export class NewContractEndpoint implements IWebServiceEndpoint { const request: NewContractRequest = req.body as NewContractRequest; const result = await this.options.plugin.newContract(request); res.send(result); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(400).json({ - message: "Bad request", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(400).json({ + message: "Bad request", + error: ex.stack || ex.message, + }); + } else { + res.status(400).json({ + message: "Bad request", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/refund-endpoint.ts b/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/refund-endpoint.ts index a838285823a..e145e81ad60 100644 --- a/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/refund-endpoint.ts +++ b/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/refund-endpoint.ts @@ -83,12 +83,19 @@ export class RefundEndpoint implements IWebServiceEndpoint { const request: RefundRequest = req.body as RefundRequest; const result = await this.options.plugin.refund(request); res.send(result); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(400).json({ - message: "Bad request", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(400).json({ + message: "Bad request", + error: ex.stack || ex.message, + }); + } else { + res.status(400).json({ + message: "Bad request", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/withdraw-endpoint.ts b/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/withdraw-endpoint.ts index 2a0bad65605..189a5904dee 100644 --- a/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/withdraw-endpoint.ts +++ b/packages/cactus-plugin-htlc-eth-besu-erc20/src/main/typescript/web-services/withdraw-endpoint.ts @@ -83,12 +83,19 @@ export class WithdrawEndpoint implements IWebServiceEndpoint { const request: WithdrawRequest = req.body as WithdrawRequest; const result = await this.options.plugin.withdraw(request); res.send(result); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(400).json({ - message: "Bad request", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(400).json({ + message: "Bad request", + error: ex.stack || ex.message, + }); + } else { + res.status(400).json({ + message: "Bad request", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/get-single-status-endpoint.ts b/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/get-single-status-endpoint.ts index fe3153fe158..b3cc2aedbe8 100644 --- a/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/get-single-status-endpoint.ts +++ b/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/get-single-status-endpoint.ts @@ -91,12 +91,19 @@ export class GetSingleStatusEndpoint implements IWebServiceEndpoint { res.status(200); res.send(callOutput); } - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/get-status-endpoint.ts b/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/get-status-endpoint.ts index cc8d3ac578f..3e2a33f18d1 100644 --- a/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/get-status-endpoint.ts +++ b/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/get-status-endpoint.ts @@ -88,12 +88,19 @@ export class GetStatusEndpoint implements IWebServiceEndpoint { res.status(200); res.send(callOutput); } - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/initialize-endpoint.ts b/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/initialize-endpoint.ts index 0bd31291e84..b1f3401cd4f 100644 --- a/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/initialize-endpoint.ts +++ b/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/initialize-endpoint.ts @@ -92,12 +92,19 @@ export class InitializeEndpoint implements IWebServiceEndpoint { res.status(200); res.send(result); } - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/new-contract-endpoint.ts b/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/new-contract-endpoint.ts index 9503c6e3d22..6ed4601059e 100644 --- a/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/new-contract-endpoint.ts +++ b/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/new-contract-endpoint.ts @@ -15,6 +15,7 @@ import { registerWebServiceEndpoint } from "@hyperledger/cactus-core"; import { NewContractObj } from "../generated/openapi/typescript-axios/api"; import { PluginHtlcEthBesu } from "../plugin-htlc-eth-besu"; import OAS from "../../json/openapi.json"; + export interface INewContractEndpointOptions { logLevel?: LogLevelDesc; plugin: PluginHtlcEthBesu; @@ -90,12 +91,19 @@ export class NewContractEndpoint implements IWebServiceEndpoint { res.status(200); res.send(result); } - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/refund-endpoint.ts b/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/refund-endpoint.ts index 42876a41d1f..aa4169c817b 100644 --- a/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/refund-endpoint.ts +++ b/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/refund-endpoint.ts @@ -90,12 +90,19 @@ export class RefundEndpoint implements IWebServiceEndpoint { } else { res.send(result); } - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/withdraw-endpoint.ts b/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/withdraw-endpoint.ts index ee443d4f25f..38ebe729885 100644 --- a/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/withdraw-endpoint.ts +++ b/packages/cactus-plugin-htlc-eth-besu/src/main/typescript/web-services/withdraw-endpoint.ts @@ -89,12 +89,19 @@ export class WithdrawEndpoint implements IWebServiceEndpoint { } else { res.send(result); } - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/plugin-keychain-aws-sm.ts b/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/plugin-keychain-aws-sm.ts index 5dcd30dd042..140393b93d5 100644 --- a/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/plugin-keychain-aws-sm.ts +++ b/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/plugin-keychain-aws-sm.ts @@ -29,6 +29,8 @@ import { SetKeychainEntryV1Endpoint } from "./webservices/set-keychain-entry-end import { GetKeychainEntryV1Endpoint } from "./webservices/get-keychain-entry-endpoint-v1"; import { DeleteKeychainEntryV1Endpoint } from "./webservices/delete-keychain-entry-endpoint-v1"; import { HasKeychainEntryV1Endpoint } from "./webservices/has-keychain-entry-endpoint-v1"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; export enum AwsCredentialType { LocalFile = "LOCAL_FILE", @@ -228,17 +230,25 @@ export class PluginKeychainAwsSm `${fnTag}: Invalid response received from AWS SecretsManager. Expected "response.SecretString" property chain to be truthy`, ); } - } catch (ex) { - const errorStatus = (ex as Error).message.includes( - SECRETMANAGER_STATUS_KEY_NOT_FOUND, - ); - if (errorStatus) { - // FIXME: Throw if the value was not present instead of returning null - //return (null as unknown) as string; - throw new Error(`${key} secret not found`); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + const errorStatus = (ex as Error).message.includes( + SECRETMANAGER_STATUS_KEY_NOT_FOUND, + ); + if (errorStatus) { + // FIXME: Throw if the value was not present instead of returning null + return (null as unknown) as string; + } else { + this.log.error(`Error retriving secret value for the key "${key}"`); + throw ex; + } + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); } else { - this.log.error(`Error retriving secret value for the key "${key}"`); - throw ex; + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); } } } @@ -253,15 +263,24 @@ export class PluginKeychainAwsSm }) .promise(); return true; - } catch (ex) { - const errorStatus = (ex as Error).message.includes( - SECRETMANAGER_STATUS_KEY_NOT_FOUND, - ); - if (errorStatus) { - return false; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + const errorStatus = (ex as Error).message.includes( + SECRETMANAGER_STATUS_KEY_NOT_FOUND, + ); + if (errorStatus) { + return false; + } else { + this.log.error(`${fnTag}: Presence check of "${key}" crashed:`, ex); + throw ex; + } + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); } else { - this.log.error(`${fnTag}: Presence check of "${key}" crashed:`, ex); - throw ex; + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); } } } @@ -276,9 +295,18 @@ export class PluginKeychainAwsSm SecretString: value, }) .promise(); - } catch (ex) { - this.log.error(` ${fnTag}: Error writing secret "${key}"`); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(` ${fnTag}: Error writing secret "${key}"`); + throw ex; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } @@ -292,9 +320,18 @@ export class PluginKeychainAwsSm ForceDeleteWithoutRecovery: true, }) .promise(); - } catch (ex) { - this.log.error(`${fnTag} Error deleting secret "${key}"`); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`${fnTag} Error deleting secret "${key}"`); + throw ex; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } } diff --git a/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/delete-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/delete-keychain-entry-endpoint-v1.ts index 2c1743755c3..7f3f5658175 100644 --- a/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/delete-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/delete-keychain-entry-endpoint-v1.ts @@ -91,12 +91,20 @@ export class DeleteKeychainEntryV1Endpoint implements IWebServiceEndpoint { const { key } = req.body as DeleteKeychainEntryRequestV1; const resBody = await this.options.connector.delete(key); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + this.log.error(`Crash while serving ${reqTag}`, ex); + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/get-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/get-keychain-entry-endpoint-v1.ts index 1a3f70036c8..c2afd6440b9 100644 --- a/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/get-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/get-keychain-entry-endpoint-v1.ts @@ -92,17 +92,21 @@ export class GetKeychainEntryV1Endpoint implements IWebServiceEndpoint { const value = await this.options.connector.get(key); //const resBody = await this.options.connector.get(reqBody.key); res.json({ key, value }); - } catch (ex) { - if (ex?.message?.includes(`${key} secret not found`)) { + } catch (ex: unknown) { + if ( + ex instanceof Error && + ex.message.includes(`${key} secret not found`) + ) { res.status(404).json({ key, - error: ex?.stack || ex?.message, + error: ex.stack || ex.message, }); } else { + const error = ex instanceof Error ? ex.stack : JSON.stringify(ex); this.log.error(`Crash while serving ${reqTag}`, ex); res.status(500).json({ message: "Internal Server Error", - error: ex?.stack || ex?.message, + error, }); } } diff --git a/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/has-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/has-keychain-entry-endpoint-v1.ts index 20b34bdb368..d176626524a 100644 --- a/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/has-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/has-keychain-entry-endpoint-v1.ts @@ -97,12 +97,19 @@ export class HasKeychainEntryV1Endpoint implements IWebServiceEndpoint { checkedAt, }; res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/set-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/set-keychain-entry-endpoint-v1.ts index 7f6608d9d79..8e788af67d8 100644 --- a/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/set-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-aws-sm/src/main/typescript/webservices/set-keychain-entry-endpoint-v1.ts @@ -90,12 +90,19 @@ export class SetKeychainEntryV1Endpoint implements IWebServiceEndpoint { const { key, value } = req.body as SetKeychainEntryRequest; const resBody = await this.options.connector.set(key, value); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-keychain-aws-sm/src/test/typescript/integration/plugin-keychain-aws-sm.test.ts b/packages/cactus-plugin-keychain-aws-sm/src/test/typescript/integration/plugin-keychain-aws-sm.test.ts index 75102f4c6f3..980c725acd7 100644 --- a/packages/cactus-plugin-keychain-aws-sm/src/test/typescript/integration/plugin-keychain-aws-sm.test.ts +++ b/packages/cactus-plugin-keychain-aws-sm/src/test/typescript/integration/plugin-keychain-aws-sm.test.ts @@ -33,6 +33,7 @@ import fs from "fs"; import path from "path"; import os from "os"; import { PluginRegistry } from "@hyperledger/cactus-core"; +import axios from "axios"; const logLevel: LogLevelDesc = "TRACE"; @@ -156,17 +157,21 @@ test("get,set,has,delete alters state as expected", async (t: Test) => { t.fail( "Failing because getKeychainEntryV1 did not throw when called with non-existent key.", ); - } catch (ex) { - t.ok(ex, "res7 -> ex truthy"); - const res7 = ex.response; - t.equal(res7.status, 404, "res7.status === 404 OK"); - t.ok(res7.data, "res7.data truthy OK"); - t.ok(res7.data.error, "res7.data.error truthy OK"); - t.equal(typeof res7.data.error, "string", "res7.data.error truthy OK"); - t.true( - res7.data.error.includes(`${key} secret not found`), - "res7.data.error contains legible error message about missing key OK", - ); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + t.ok(ex, "res7 -> ex truthy"); + const res7 = ex.response; + t.equal(res7?.status, 404, "res7.status === 404 OK"); + t.ok(res7?.data, "res7.data truthy OK"); + t.ok(res7?.data.error, "res7.data.error truthy OK"); + t.equal(typeof res7?.data.error, "string", "res7.data.error truthy OK"); + t.true( + res7?.data.error.includes(`${key} secret not found`), + "res7.data.error contains legible error message about missing key OK", + ); + } else { + t.fail("expected an axios error, got something else"); + } } } diff --git a/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/delete-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/delete-keychain-entry-endpoint-v1.ts index 769297fe165..6a0f872c578 100644 --- a/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/delete-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/delete-keychain-entry-endpoint-v1.ts @@ -89,12 +89,19 @@ export class DeleteKeychainEntryV1Endpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.delete(reqBody.key); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/get-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/get-keychain-entry-endpoint-v1.ts index 1366b55029d..23ad37f6f15 100644 --- a/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/get-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/get-keychain-entry-endpoint-v1.ts @@ -89,17 +89,18 @@ export class GetKeychainEntryV1Endpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.get(reqBody.key); res.json(resBody); - } catch (ex) { - if (ex.message.includes("secret not found")) { + } catch (ex: unknown) { + if (ex instanceof Error && ex.message.includes("secret not found")) { res.status(404).json({ message: "Bad request", - error: ex?.stack || ex?.message, + error: ex.stack || ex.message, }); } else { + const error = ex instanceof Error ? ex.stack : JSON.stringify(ex); this.log.error(`Crash while serving ${reqTag}`, ex); res.status(500).json({ message: "Internal Server Error", - error: ex?.stack || ex?.message, + error, }); } } diff --git a/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/has-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/has-keychain-entry-endpoint-v1.ts index a26f9bbcf30..704238541ce 100644 --- a/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/has-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/has-keychain-entry-endpoint-v1.ts @@ -91,12 +91,19 @@ export class HasKeychainEntryV1Endpoint implements IWebServiceEndpoint { const isPresent = await this.options.connector.has(reqBody.key); const checkedAt = new Date().toJSON(); res.json({ key, isPresent, checkedAt }); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/set-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/set-keychain-entry-endpoint-v1.ts index d5dfe171fec..e3bddaa9a7e 100644 --- a/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/set-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-google-sm/src/main/typescript/webservices/set-keychain-entry-endpoint-v1.ts @@ -92,12 +92,19 @@ export class SetKeychainEntryV1Endpoint implements IWebServiceEndpoint { reqBody.value, ); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-keychain-google-sm/src/test/typescript/integration/openapi/openapi-validation.test.ts b/packages/cactus-plugin-keychain-google-sm/src/test/typescript/integration/openapi/openapi-validation.test.ts index 8f157f02f4b..5fc3470cffc 100644 --- a/packages/cactus-plugin-keychain-google-sm/src/test/typescript/integration/openapi/openapi-validation.test.ts +++ b/packages/cactus-plugin-keychain-google-sm/src/test/typescript/integration/openapi/openapi-validation.test.ts @@ -26,6 +26,7 @@ import { SecretManagerServiceClientMock } from "../../mock/plugin-keychain-googl import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core"; import OAS from "../../../../main/json/openapi.json"; +import axios from "axios"; const logLevel: LogLevelDesc = "TRACE"; const testCase = "Test cactus-plugin-keychain-azure-kv openapi validation"; @@ -112,16 +113,20 @@ test(testCase, async (t: Test) => { await apiClient.setKeychainEntryV1(({ value, } as any) as SetKeychainEntryRequestV1); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fSet} without required key: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("key"), "Rejected because key is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fSet} without required key: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("key"), "Rejected because key is required"); + } else if (e instanceof Error) { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); @@ -131,16 +136,20 @@ test(testCase, async (t: Test) => { await apiClient.getKeychainEntryV1( ({} as any) as GetKeychainEntryRequestV1, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fGet} without required key: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("key"), "Rejected because key is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fGet} without required key: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("key"), "Rejected because key is required"); + } else { + t2.fail("expected an axios error got something else"); + } } t2.end(); }); @@ -150,16 +159,20 @@ test(testCase, async (t: Test) => { await apiClient.hasKeychainEntryV1( ({} as any) as HasKeychainEntryRequestV1, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fHas} without required key: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("key"), "Rejected because key is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fHas} without required key: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("key"), "Rejected because key is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); @@ -169,16 +182,20 @@ test(testCase, async (t: Test) => { await apiClient.deleteKeychainEntryV1( ({} as any) as DeleteKeychainEntryRequestV1, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fDelete} without required key: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("key"), "Rejected because key is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDelete} without required key: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("key"), "Rejected because key is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); @@ -190,19 +207,23 @@ test(testCase, async (t: Test) => { value, fake: 4, } as any) as SetKeychainEntryRequestV1); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fSet} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fSet} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); @@ -213,19 +234,23 @@ test(testCase, async (t: Test) => { key, fake: 4, } as any) as GetKeychainEntryRequestV1); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fGet} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fGet} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); @@ -236,19 +261,23 @@ test(testCase, async (t: Test) => { key, fake: 4, } as any) as HasKeychainEntryRequestV1); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fHas} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fHas} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); @@ -259,19 +288,23 @@ test(testCase, async (t: Test) => { key, fake: 4, } as any) as DeleteKeychainEntryRequestV1); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fDelete} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDelete} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); diff --git a/packages/cactus-plugin-keychain-google-sm/src/test/typescript/integration/plugin-keychain-google-sm.test.ts b/packages/cactus-plugin-keychain-google-sm/src/test/typescript/integration/plugin-keychain-google-sm.test.ts index c0705d6db66..d36cf382629 100644 --- a/packages/cactus-plugin-keychain-google-sm/src/test/typescript/integration/plugin-keychain-google-sm.test.ts +++ b/packages/cactus-plugin-keychain-google-sm/src/test/typescript/integration/plugin-keychain-google-sm.test.ts @@ -22,6 +22,7 @@ import { } from "../../../main/typescript/generated/openapi/typescript-axios/index"; import { SecretManagerServiceClientMock } from "../mock/plugin-keychain-google-sm-mock"; +import axios from "axios"; const logLevel: LogLevelDesc = "TRACE"; @@ -114,23 +115,25 @@ test("get,set,has,delete alters state as expected", async (t: Test) => { t.equal(res6.data.key, key, "res6.data.key === key OK"); try { await apiClient.getKeychainEntryV1({ key }); - } catch (out) { - t.ok(out, "error thrown for not found endpoint truthy OK"); - t.ok(out.response, "deploy contract response truthy OK"); - t.ok(out.response.data, "out.response.data truthy OK"); - t.ok(out.response.data.error, "out.response.data.error truthy OK"); - t.true( - out.response.data.error.includes(`${key} secret not found`), - "HTTP 404 response for non-existent key contains legible error message OK", - ); - - t.equal( - out.response.status, - StatusCodes.NOT_FOUND, - "deploy contract response status === 404 OK", - ); - t.notok(out.response.data.success, "out.response.data.success falsy OK"); + } catch (out: unknown) { + if (axios.isAxiosError(out)) { + t.ok(out, "error thrown for not found endpoint truthy OK"); + t.ok(out.response, "deploy contract response truthy OK"); + t.ok(out.response?.data, "out.response.data truthy OK"); + t.ok(out.response?.data.error, "out.response.data.error truthy OK"); + t.true( + out.response?.data.error.includes(`${key} secret not found`), + "HTTP 404 response for non-existent key contains legible error message OK", + ); + t.equal( + out.response?.status, + StatusCodes.NOT_FOUND, + "deploy contract response status === 404 OK", + ); + t.notok(out.response?.data.success, "out.response.data.success falsy OK"); + } else { + t.fail("expected an axios error, got something else"); + } } - t.end(); }); diff --git a/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/delete-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/delete-keychain-entry-endpoint-v1.ts index b5c1a4427f9..98c586db479 100644 --- a/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/delete-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/delete-keychain-entry-endpoint-v1.ts @@ -90,12 +90,19 @@ export class DeleteKeychainEntryV1Endpoint implements IWebServiceEndpoint { const { key } = req.body as DeleteKeychainEntryRequestV1; const resBody = await this.options.plugin.delete(key); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex?.stack || ex?.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/get-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/get-keychain-entry-endpoint-v1.ts index e09aee8e757..3406a4ebe12 100644 --- a/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/get-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/get-keychain-entry-endpoint-v1.ts @@ -90,8 +90,11 @@ export class GetKeychainEntryV1Endpoint implements IWebServiceEndpoint { try { const value = await this.options.plugin.get(key); res.json({ key, value }); - } catch (ex) { - if (ex?.message?.includes(`${key} secret not found`)) { + } catch (ex: unknown) { + if ( + ex instanceof Error && + ex?.message?.includes(`${key} secret not found`) + ) { res.status(404).json({ key, error: ex?.stack || ex?.message, @@ -100,7 +103,7 @@ export class GetKeychainEntryV1Endpoint implements IWebServiceEndpoint { this.log.error(`Crash while serving ${reqTag}`, ex); res.status(500).json({ message: "Internal Server Error", - error: ex?.stack || ex?.message, + error: JSON.stringify(ex), }); } } diff --git a/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/has-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/has-keychain-entry-endpoint-v1.ts index 4d2f450b580..c96d9a78c46 100644 --- a/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/has-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/has-keychain-entry-endpoint-v1.ts @@ -97,12 +97,19 @@ export class HasKeychainEntryV1Endpoint implements IWebServiceEndpoint { checkedAt, }; res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex?.stack || ex?.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/set-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/set-keychain-entry-endpoint-v1.ts index 1138d884b98..da627aec752 100644 --- a/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/set-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-memory-wasm/src/main/typescript/webservices/set-keychain-entry-endpoint-v1.ts @@ -92,10 +92,17 @@ export class SetKeychainEntryV1Endpoint implements IWebServiceEndpoint { res.json(resBody); } catch (ex) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex?.stack || ex?.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-keychain-memory/src/main/typescript/get-prometheus-exporter-metrics/get-prometheus-exporter-metrics-endpoint-v1.ts b/packages/cactus-plugin-keychain-memory/src/main/typescript/get-prometheus-exporter-metrics/get-prometheus-exporter-metrics-endpoint-v1.ts index 99be7a2e396..a48980b404e 100644 --- a/packages/cactus-plugin-keychain-memory/src/main/typescript/get-prometheus-exporter-metrics/get-prometheus-exporter-metrics-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-memory/src/main/typescript/get-prometheus-exporter-metrics/get-prometheus-exporter-metrics-endpoint-v1.ts @@ -91,11 +91,17 @@ export class GetPrometheusExporterMetricsEndpointV1 const resBody = await this.opts.plugin.getPrometheusExporterMetrics(); res.status(200); res.send(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-keychain-vault/src/main/typescript/plugin-keychain-vault-remote-adapter.ts b/packages/cactus-plugin-keychain-vault/src/main/typescript/plugin-keychain-vault-remote-adapter.ts index ae0838b1ad7..e20258c360f 100644 --- a/packages/cactus-plugin-keychain-vault/src/main/typescript/plugin-keychain-vault-remote-adapter.ts +++ b/packages/cactus-plugin-keychain-vault/src/main/typescript/plugin-keychain-vault-remote-adapter.ts @@ -16,6 +16,8 @@ import { } from "@hyperledger/cactus-core-api"; import { DefaultApi } from "./generated/openapi/typescript-axios"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; export interface IPluginKeychainVaultRemoteAdapterOptions extends ICactusPluginOptions { @@ -106,10 +108,19 @@ export class PluginKeychainVaultRemoteAdapter try { await this.backend.getKeychainEntryV1({ key }); return true; - } catch (ex) { + } catch (ex: unknown) { // FIXME check for errors being thrown due to something other than // the key not being present... - return false; + if (axios.isAxiosError(ex)) { + return false; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } diff --git a/packages/cactus-plugin-keychain-vault/src/main/typescript/plugin-keychain-vault.ts b/packages/cactus-plugin-keychain-vault/src/main/typescript/plugin-keychain-vault.ts index 1135274f7b5..069394a979b 100644 --- a/packages/cactus-plugin-keychain-vault/src/main/typescript/plugin-keychain-vault.ts +++ b/packages/cactus-plugin-keychain-vault/src/main/typescript/plugin-keychain-vault.ts @@ -27,6 +27,8 @@ import { GetKeychainEntryEndpointV1 } from "./web-services/get-keychain-entry-en import { SetKeychainEntryEndpointV1 } from "./web-services/set-keychain-entry-endpoint-v1"; import { HasKeychainEntryEndpointV1 } from "./web-services/has-keychain-entry-endpoint-v1"; import { DeleteKeychainEntryEndpointV1 } from "./web-services/delete-keychain-entry-endpoint-v1"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; export interface IPluginKeychainVaultOptions extends ICactusPluginOptions { logLevel?: LogLevelDesc; @@ -227,13 +229,22 @@ export class PluginKeychainVault implements IPluginWebService, IPluginKeychain { `${fnTag}: Invalid response received from Vault. Expected "response.data.data.value" property chain to be truthy`, ); } - } catch (ex) { - // FIXME: Throw if not found, detect it in the endpoint code, status=404 - if (ex?.response?.statusCode === HttpStatus.NOT_FOUND) { - return (null as unknown) as string; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + // FIXME: Throw if not found, detect it in the endpoint code, status=404 + if (ex?.response?.status === HttpStatus.NOT_FOUND) { + return (null as unknown) as string; + } else { + this.log.error(`Retrieval of "${key}" crashed:`, ex); + throw ex; + } + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); } else { - this.log.error(`Retrieval of "${key}" crashed:`, ex); - throw ex; + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); } } } @@ -249,18 +260,24 @@ export class PluginKeychainVault implements IPluginWebService, IPluginKeychain { try { const res = await this.backend.read(path); return res; - } catch (ex) { - // We have to make sure that the exception is either an expected - // or an unexpected one where the expected exception is what we - // get when the key is not present in the keychain and anything - // else being an unexpected exception that we do not want to - // handle nor suppress under any circumstances since doing so - // would lead to silent failures or worse. - if (ex?.response?.statusCode === HttpStatus.NOT_FOUND) { - return false; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + // We have to make sure that the exception is either an expected + // or an unexpected one where the expected exception is what we + // get when the key is not present in the keychain and anything + // else being an unexpected exception that we do not want to + // handle nor suppress under any circumstances since doing so + // would lead to silent failures or worse. + if (ex?.response?.status === HttpStatus.NOT_FOUND) { + return false; + } else { + this.log.error(`Presence check of "${key}" crashed:`, ex); + throw ex; + } + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); } else { - this.log.error(`Presence check of "${key}" crashed:`, ex); - throw ex; + throw new RuntimeError("unexpected exception with incorrect type"); } } } diff --git a/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/delete-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/delete-keychain-entry-endpoint-v1.ts index 250a4fd2463..74c87005678 100644 --- a/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/delete-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/delete-keychain-entry-endpoint-v1.ts @@ -99,10 +99,15 @@ export class DeleteKeychainEntryEndpointV1 implements IWebServiceEndpoint { }; res.status(200); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.debug(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/get-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/get-keychain-entry-endpoint-v1.ts index 1d2f22d67ff..184b286bc24 100644 --- a/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/get-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/get-keychain-entry-endpoint-v1.ts @@ -100,10 +100,15 @@ export class GetKeychainEntryEndpointV1 implements IWebServiceEndpoint { }; res.status(200); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.debug(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts b/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts index 65a68e5dac2..bfbb342bd72 100644 --- a/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts @@ -91,11 +91,17 @@ export class GetPrometheusExporterMetricsEndpointV1 const resBody = await this.opts.plugin.getPrometheusExporterMetrics(); res.status(200); res.send(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/has-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/has-keychain-entry-endpoint-v1.ts index 2af9d33d2f2..b10c5326fc4 100644 --- a/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/has-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/has-keychain-entry-endpoint-v1.ts @@ -101,10 +101,15 @@ export class HasKeychainEntryEndpointV1 implements IWebServiceEndpoint { }; res.status(200); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.debug(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/set-keychain-entry-endpoint-v1.ts b/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/set-keychain-entry-endpoint-v1.ts index 2f4de99a243..4d74d9cc58f 100644 --- a/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/set-keychain-entry-endpoint-v1.ts +++ b/packages/cactus-plugin-keychain-vault/src/main/typescript/web-services/set-keychain-entry-endpoint-v1.ts @@ -95,10 +95,15 @@ export class SetKeychainEntryEndpointV1 implements IWebServiceEndpoint { const resBody = await this.plugin.set(key, value); res.status(200); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.debug(`${tag} Failed to serve request:`, ex); - res.status(500); - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.json({ error: ex.stack }); + } else { + res.status(500); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-keychain-vault/src/test/typescript/integration/openapi/openapi-validation.test.ts b/packages/cactus-plugin-keychain-vault/src/test/typescript/integration/openapi/openapi-validation.test.ts index 932977729e8..fffae30599f 100644 --- a/packages/cactus-plugin-keychain-vault/src/test/typescript/integration/openapi/openapi-validation.test.ts +++ b/packages/cactus-plugin-keychain-vault/src/test/typescript/integration/openapi/openapi-validation.test.ts @@ -32,6 +32,7 @@ import { DefaultApi as KeychainVaultApi } from "../../../../main/typescript/publ import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core"; import OAS from "../../../../main/json/openapi.json"; +import axios from "axios"; const logLevel: LogLevelDesc = "TRACE"; const testCase = "cactus-plugin-keychain-vault API"; @@ -139,71 +140,90 @@ test(`${testCase}`, async (t: Test) => { await apiClient.setKeychainEntryV1({ value: value1, } as SetKeychainEntryRequest); - } catch (err) { - const e = err as AxiosError<{ path: string }[]>; - t2.equal( - e?.response?.status, - 400, - `Endpoint ${fSet} without required key: response.status === 400 OK`, - ); - const fields = e?.response?.data.map((param) => - param.path.replace(".body.", ""), - ); - t2.ok(fields?.includes("key"), "Rejected because key is required"); + } catch (err: unknown) { + if (err instanceof Error) { + const e = err as AxiosError<{ path: string }[]>; + t2.equal( + e?.response?.status, + 400, + `Endpoint ${fSet} without required key: response.status === 400 OK`, + ); + const fields = e?.response?.data.map((param) => + param.path.replace(".body.", ""), + ); + t2.ok(fields?.includes("key"), "Rejected because key is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); test(`${testCase} - ${fHas} - ${cWithoutParams}`, async (t2: Test) => { try { - await apiClient.hasKeychainEntryV1({} as HasKeychainEntryRequestV1); - } catch (err) { - const e = err as AxiosError<{ path: string }[]>; - t2.equal( - e?.response?.status, - 400, - `Endpoint ${fHas} without required key: response.status === 400 OK`, + await apiClient.hasKeychainEntryV1( + ({} as any) as HasKeychainEntryRequestV1, ); - const fields = e?.response?.data.map((param) => - param.path.replace(".body.", ""), - ); - t2.ok(fields?.includes("key"), "Rejected because key is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fHas} without required key: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("key"), "Rejected because key is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); test(`${testCase} - ${fGet} - ${cWithoutParams}`, async (t2: Test) => { try { - await apiClient.getKeychainEntryV1({} as GetKeychainEntryRequest); - } catch (err) { - const e = err as AxiosError<{ path: string }[]>; - t2.equal( - e?.response?.status, - 400, - `Endpoint ${fGet} without required key: response.status === 400 OK`, - ); - const fields = e?.response?.data.map((param) => - param.path.replace(".body.", ""), + await apiClient.getKeychainEntryV1( + ({} as any) as GetKeychainEntryRequest, ); - t2.ok(fields?.includes("key"), "Rejected because key is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fGet} without required key: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("key"), "Rejected because key is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); test(`${testCase} - ${fDelete} - ${cWithoutParams}`, async (t2: Test) => { try { - await apiClient.deleteKeychainEntryV1({} as DeleteKeychainEntryRequestV1); - } catch (err) { - const e = err as AxiosError<{ path: string }[]>; - t2.equal( - e?.response?.status, - 400, - `Endpoint ${fDelete} without required key: response.status === 400 OK`, + await apiClient.deleteKeychainEntryV1( + ({} as any) as DeleteKeychainEntryRequestV1, ); - const fields = e?.response?.data.map((param) => - param.path.replace(".body.", ""), - ); - t2.ok(fields?.includes("key"), "Rejected because key is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDelete} without required key: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("key"), "Rejected because key is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); @@ -215,20 +235,24 @@ test(`${testCase}`, async (t: Test) => { value: value1, fake: 4, } as SetKeychainEntryRequest); - } catch (err) { - const e = err as AxiosError<{ path: string }[]>; - t2.equal( - e?.response?.status, - 400, - `Endpoint ${fSet} with fake=4: response.status === 400 OK`, - ); - const fields = e?.response?.data.map((param) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields?.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (err: unknown) { + if (err instanceof Error) { + const e = err as AxiosError<{ path: string }[]>; + t2.equal( + e?.response?.status, + 400, + `Endpoint ${fSet} with fake=4: response.status === 400 OK`, + ); + const fields = e?.response?.data.map((param) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields?.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); @@ -239,20 +263,24 @@ test(`${testCase}`, async (t: Test) => { key: key1, fake: 4, } as HasKeychainEntryRequestV1); - } catch (err) { - const e = err as AxiosError<{ path: string }[]>; - t2.equal( - e?.response?.status, - 400, - `Endpoint ${fHas} with fake=4: response.status === 400 OK`, - ); - const fields = e?.response?.data.map((param) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields?.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (err: unknown) { + if (err instanceof Error) { + const e = err as AxiosError<{ path: string }[]>; + t2.equal( + e?.response?.status, + 400, + `Endpoint ${fHas} with fake=4: response.status === 400 OK`, + ); + const fields = e?.response?.data.map((param) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields?.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); @@ -263,20 +291,24 @@ test(`${testCase}`, async (t: Test) => { key: key1, fake: 4, } as GetKeychainEntryRequest); - } catch (err) { - const e = err as AxiosError<{ path: string }[]>; - t2.equal( - e?.response?.status, - 400, - `Endpoint ${fGet} with fake=4: response.status === 400 OK`, - ); - const fields = - e?.response?.data.map((param) => param.path.replace(".body.", "")) || - []; - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (err: unknown) { + if (err instanceof Error) { + const e = err as AxiosError<{ path: string }[]>; + t2.equal( + e?.response?.status, + 400, + `Endpoint ${fGet} with fake=4: response.status === 400 OK`, + ); + const fields = + e?.response?.data.map((param) => param.path.replace(".body.", "")) || + []; + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); @@ -287,20 +319,24 @@ test(`${testCase}`, async (t: Test) => { key: key1, fake: 4, } as GetKeychainEntryRequest); - } catch (err) { - const e = err as AxiosError; - t2.equal( - (e as AxiosError)?.response?.status, - 400, - `Endpoint ${fDelete} with fake=4: response.status === 400 OK`, - ); - const fields = e?.response?.data.map((param: { path: string }) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields?.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (err: unknown) { + if (err instanceof Error) { + const e = err as AxiosError; + t2.equal( + (e as AxiosError)?.response?.status, + 400, + `Endpoint ${fDelete} with fake=4: response.status === 400 OK`, + ); + const fields = e?.response?.data.map((param: { path: string }) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields?.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); diff --git a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint.ts b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint.ts index cfd4b68349f..e3486870288 100644 --- a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint.ts +++ b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint.ts @@ -91,12 +91,19 @@ export class DeployContractSolidityBytecodeEndpoint try { const resBody = await this.options.connector.deployContract(reqBody); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-balance-endpoint.ts b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-balance-endpoint.ts index 34664ba566e..09569d2a93d 100644 --- a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-balance-endpoint.ts +++ b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-balance-endpoint.ts @@ -88,12 +88,19 @@ export class GetBalanceEndpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.getBalance(reqBody); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-besu-record-endpoint-v1.ts b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-besu-record-endpoint-v1.ts index f40e93d2e91..3aaf76dc692 100644 --- a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-besu-record-endpoint-v1.ts +++ b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-besu-record-endpoint-v1.ts @@ -91,12 +91,19 @@ export class GetBesuRecordEndpointV1 implements IWebServiceEndpoint { const reqBody: GetBesuRecordV1Request = req.body as GetBesuRecordV1Request; const resBody = await this.options.connector.getBesuRecord(reqBody); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-block-v1-endpoint-.ts b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-block-v1-endpoint-.ts index 826723a7273..d5a4b36bd20 100644 --- a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-block-v1-endpoint-.ts +++ b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-block-v1-endpoint-.ts @@ -88,12 +88,19 @@ export class GetBlockEndpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.getBlock(reqBody); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-past-logs-endpoint.ts b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-past-logs-endpoint.ts index 2537152b27c..a7393fcbb54 100644 --- a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-past-logs-endpoint.ts +++ b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-past-logs-endpoint.ts @@ -88,12 +88,19 @@ export class GetPastLogsEndpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.getPastLogs(reqBody); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts index 55541efa1dc..ecf2bad1c38 100644 --- a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts +++ b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts @@ -90,11 +90,17 @@ export class GetPrometheusExporterMetricsEndpointV1 const resBody = await this.options.connector.getPrometheusExporterMetrics(); res.status(200); res.send(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-transaction-endpoint.ts b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-transaction-endpoint.ts index 5c7f8960945..1fa1ee403a4 100644 --- a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-transaction-endpoint.ts +++ b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/get-transaction-endpoint.ts @@ -88,12 +88,19 @@ export class GetTransactionEndpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.getTransaction(reqBody); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/invoke-contract-endpoint.ts b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/invoke-contract-endpoint.ts index cf5e9aa3e1b..22accb525e1 100644 --- a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/invoke-contract-endpoint.ts +++ b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/invoke-contract-endpoint.ts @@ -89,12 +89,19 @@ export class InvokeContractEndpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.invokeContract(reqBody); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/run-transaction-endpoint.ts b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/run-transaction-endpoint.ts index 6a5b05e20ac..1ce1baf3271 100644 --- a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/run-transaction-endpoint.ts +++ b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/run-transaction-endpoint.ts @@ -89,12 +89,19 @@ export class RunTransactionEndpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.transact(reqBody); res.json({ success: true, data: resBody }); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/sign-transaction-endpoint-v1.ts b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/sign-transaction-endpoint-v1.ts index 7f9e0984c43..83c2b373860 100644 --- a/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/sign-transaction-endpoint-v1.ts +++ b/packages/cactus-plugin-ledger-connector-besu/src/main/typescript/web-services/sign-transaction-endpoint-v1.ts @@ -97,11 +97,17 @@ export class BesuSignTransactionEndpointV1 implements IWebServiceEndpoint { res.statusMessage = "Transaction not found"; res.json({ error: "Transaction not found" }); } - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-besu/src/test/typescript/integration/plugin-ledger-connector-besu/openapi/openapi-validation.test.ts b/packages/cactus-plugin-ledger-connector-besu/src/test/typescript/integration/plugin-ledger-connector-besu/openapi/openapi-validation.test.ts index d7386637bc5..5ceb351123a 100644 --- a/packages/cactus-plugin-ledger-connector-besu/src/test/typescript/integration/plugin-ledger-connector-besu/openapi/openapi-validation.test.ts +++ b/packages/cactus-plugin-ledger-connector-besu/src/test/typescript/integration/plugin-ledger-connector-besu/openapi/openapi-validation.test.ts @@ -41,6 +41,7 @@ import { BesuApiClientOptions } from "../../../../../main/typescript/api-client/ import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core"; import OAS from "../../../../../main/json/openapi.json"; +import axios from "axios"; const logLevel: LogLevelDesc = "TRACE"; const testCase = "Besu API"; @@ -200,26 +201,29 @@ test(testCase, async (t: Test) => { await apiClient.deployContractSolBytecodeV1( (parameters as any) as DeployContractSolidityBytecodeV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fDeploy} without required contractName and bytecode: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("contractName"), - "Rejected because contractName is required", - ); - t2.ok( - fields.includes("bytecode"), - "Rejected because bytecode is required", - ); - t2.notOk(fields.includes("gas"), "gas is not required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDeploy} without required contractName and bytecode: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("contractName"), + "Rejected because contractName is required", + ); + t2.ok( + fields.includes("bytecode"), + "Rejected because bytecode is required", + ); + t2.notOk(fields.includes("gas"), "gas is not required"); + } else { + t2.fail(JSON.stringify(e)); + } } - t2.end(); }); @@ -242,22 +246,25 @@ test(testCase, async (t: Test) => { await apiClient.deployContractSolBytecodeV1( parameters as DeployContractSolidityBytecodeV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fDeploy} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDeploy} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("excepted an axios error, got something else"); + } + t2.end(); } - - t2.end(); }); test(`${testCase} - ${fInvoke} - ${cOk}`, async (t2: Test) => { @@ -303,22 +310,25 @@ test(testCase, async (t: Test) => { await apiClient.invokeContractV1( (parameters as any) as InvokeContractV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fInvoke} without required contractName: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("contractName"), - "Rejected because contractName is required", - ); - t2.notOk(fields.includes("gas"), "gas is not required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fInvoke} without required contractName: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("contractName"), + "Rejected because contractName is required", + ); + t2.notOk(fields.includes("gas"), "gas is not required"); + } else { + t2.fail("expected an axios error, got something else"); + } } - t2.end(); }); @@ -338,21 +348,24 @@ test(testCase, async (t: Test) => { fake: 4, }; await apiClient.invokeContractV1(parameters as InvokeContractV1Request); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fInvoke} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fInvoke} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } - t2.end(); }); @@ -401,19 +414,23 @@ test(testCase, async (t: Test) => { }, }; await apiClient.runTransactionV1(parameters as RunTransactionRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRun} without required consistencyStrategy: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("consistencyStrategy"), - "Rejected because consistencyStrategy is required", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRun} without required consistencyStrategy: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("consistencyStrategy"), + "Rejected because consistencyStrategy is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -441,21 +458,24 @@ test(testCase, async (t: Test) => { fake: 4, }; await apiClient.runTransactionV1(parameters as RunTransactionRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRun} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRun} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } - t2.end(); }); @@ -542,21 +562,24 @@ test(testCase, async (t: Test) => { }; await apiClient.signTransactionV1(parameters as SignTransactionRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fSign} without required keychainId: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("keychainId"), - "Rejected because keychainId is required", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fSign} without required keychainId: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("keychainId"), + "Rejected because keychainId is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } - t2.end(); }); @@ -598,19 +621,23 @@ test(testCase, async (t: Test) => { }; await apiClient.signTransactionV1(parameters as SignTransactionRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fSign} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fSign} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error but got something else"); + } } t2.end(); @@ -633,16 +660,23 @@ test(testCase, async (t: Test) => { try { const parameters = {}; await apiClient.getBalanceV1(parameters as GetBalanceV1Request); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fBalance} without required address: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("address"), "Rejected because address is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fBalance} without required address: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("address"), + "Rejected because address is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -655,19 +689,23 @@ test(testCase, async (t: Test) => { fake: 4, }; await apiClient.getBalanceV1(parameters as GetBalanceV1Request); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fBalance} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fBalance} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -686,19 +724,23 @@ test(testCase, async (t: Test) => { try { const parameters = {}; await apiClient.getBlockV1(parameters as GetBlockV1Request); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fBlock} without required blockHashOrBlockNumber: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("blockHashOrBlockNumber"), - "Rejected because blockHashOrBlockNumber is required", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fBlock} without required blockHashOrBlockNumber: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("blockHashOrBlockNumber"), + "Rejected because blockHashOrBlockNumber is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -711,19 +753,23 @@ test(testCase, async (t: Test) => { fake: 4, }; await apiClient.getBlockV1(parameters as GetBlockV1Request); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fBlock} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fBlock} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -748,16 +794,23 @@ test(testCase, async (t: Test) => { try { const parameters = {}; await apiClient.getPastLogsV1(parameters as GetPastLogsV1Request); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fPastLogs} without required address: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("address"), "Rejected because address is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fPastLogs} without required address: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("address"), + "Rejected because address is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -770,19 +823,23 @@ test(testCase, async (t: Test) => { fake: 4, }; await apiClient.getPastLogsV1(parameters as GetPastLogsV1Request); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fPastLogs} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fPastLogs} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -838,19 +895,23 @@ test(testCase, async (t: Test) => { try { const parameters = {}; await apiClient.getBesuRecordV1(parameters as GetBesuRecordV1Request); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRecord} without required transactionHash: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("transactionHash"), - "Rejected because transactionHash is required", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRecord} without required transactionHash: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("transactionHash"), + "Rejected because transactionHash is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -863,21 +924,24 @@ test(testCase, async (t: Test) => { fake: 5, }; await apiClient.getBesuRecordV1(parameters as GetBesuRecordV1Request); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRecord} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRecord} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } - t2.end(); }); diff --git a/packages/cactus-plugin-ledger-connector-corda/src/main/typescript/web-services/deploy-contract-jars-endpoint.ts b/packages/cactus-plugin-ledger-connector-corda/src/main/typescript/web-services/deploy-contract-jars-endpoint.ts index 5a20a7479c2..912167cc3c7 100644 --- a/packages/cactus-plugin-ledger-connector-corda/src/main/typescript/web-services/deploy-contract-jars-endpoint.ts +++ b/packages/cactus-plugin-ledger-connector-corda/src/main/typescript/web-services/deploy-contract-jars-endpoint.ts @@ -129,14 +129,23 @@ export class DeployContractJarsEndpoint implements IWebServiceEndpoint { const body = await this.doDeploy(req.body); res.status(200); res.json(body); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.json({ - error: ex?.message, - // FIXME do not include stack trace - errorStack: ex?.stack, - }); + if (ex instanceof Error) { + res.status(500); + res.json({ + error: ex.message, + // FIXME do not include stack trace + errorStack: ex.stack, + }); + } else { + res.status(500); + res.json({ + error: JSON.stringify(ex), + // FIXME do not include stack trace + errorStack: JSON.stringify(ex), + }); + } } } @@ -195,8 +204,12 @@ export class DeployContractJarsEndpoint implements IWebServiceEndpoint { try { const response = await ssh.execCommand(cmd); this.log.debug(`${fnTag} stopped Corda node OK `, response); - } catch (ex) { - this.log.error(`${fnTag} stopping of Corda node failed`, ex); + } catch (ex: unknown) { + if (ex instanceof Error) { + this.log.error(`${fnTag} stopping of Corda node failed`, ex); + } else { + this.log.error(`${fnTag} stopping of Corda node failed`, ex); + } } } @@ -207,8 +220,12 @@ export class DeployContractJarsEndpoint implements IWebServiceEndpoint { try { const response = await ssh.execCommand(cmd); this.log.debug(`${fnTag} started Corda node OK `, response); - } catch (ex) { - this.log.error(`${fnTag} starting of Corda node failed`, ex); + } catch (ex: unknown) { + if (ex instanceof Error) { + this.log.error(`${fnTag} starting of Corda node failed`, ex); + } else { + this.log.error(`${fnTag} starting of Corda node failed`, ex); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-corda/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts b/packages/cactus-plugin-ledger-connector-corda/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts index e1ba119bdc8..7bd4991a4ec 100644 --- a/packages/cactus-plugin-ledger-connector-corda/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts +++ b/packages/cactus-plugin-ledger-connector-corda/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts @@ -91,11 +91,17 @@ export class GetPrometheusExporterMetricsEndpointV1 const resBody = await this.opts.connector.getPrometheusExporterMetrics(); res.status(200); res.send(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-corda/src/main/typescript/web-services/invoke-contract-endpoint-v1.ts b/packages/cactus-plugin-ledger-connector-corda/src/main/typescript/web-services/invoke-contract-endpoint-v1.ts index 24c5b3f77c8..c1e6e92db8d 100644 --- a/packages/cactus-plugin-ledger-connector-corda/src/main/typescript/web-services/invoke-contract-endpoint-v1.ts +++ b/packages/cactus-plugin-ledger-connector-corda/src/main/typescript/web-services/invoke-contract-endpoint-v1.ts @@ -87,11 +87,17 @@ export class InvokeContractEndpointV1 implements IWebServiceEndpoint { const resBody = "NOT_IMPLEMENTED"; res.status(501); res.send(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/deploy-contract-go-source/deploy-contract-go-source-endpoint-v1.ts b/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/deploy-contract-go-source/deploy-contract-go-source-endpoint-v1.ts index 18def8f1a5d..953744eac9c 100644 --- a/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/deploy-contract-go-source/deploy-contract-go-source-endpoint-v1.ts +++ b/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/deploy-contract-go-source/deploy-contract-go-source-endpoint-v1.ts @@ -95,11 +95,17 @@ export class DeployContractGoSourceEndpointV1 implements IWebServiceEndpoint { const resBody = await connector.deployContractGoSourceV1(reqBody); res.status(HttpStatus.OK); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve contract deploy request`, ex); - res.status(HttpStatus.INTERNAL_SERVER_ERROR); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(HttpStatus.INTERNAL_SERVER_ERROR); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(HttpStatus.INTERNAL_SERVER_ERROR); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/deploy-contract/deploy-contract-endpoint-v1.ts b/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/deploy-contract/deploy-contract-endpoint-v1.ts index 7d2f554bf3a..4cc2acd7b7d 100644 --- a/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/deploy-contract/deploy-contract-endpoint-v1.ts +++ b/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/deploy-contract/deploy-contract-endpoint-v1.ts @@ -95,11 +95,17 @@ export class DeployContractEndpointV1 implements IWebServiceEndpoint { const resBody = await connector.deployContract(reqBody); res.status(HttpStatus.OK); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve contract deploy request`, ex); - res.status(HttpStatus.INTERNAL_SERVER_ERROR); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(HttpStatus.INTERNAL_SERVER_ERROR); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(HttpStatus.INTERNAL_SERVER_ERROR); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/get-prometheus-exporter-metrics/get-prometheus-exporter-metrics-endpoint-v1.ts b/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/get-prometheus-exporter-metrics/get-prometheus-exporter-metrics-endpoint-v1.ts index 4e6522d293a..aef54108d30 100644 --- a/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/get-prometheus-exporter-metrics/get-prometheus-exporter-metrics-endpoint-v1.ts +++ b/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/get-prometheus-exporter-metrics/get-prometheus-exporter-metrics-endpoint-v1.ts @@ -90,11 +90,17 @@ export class GetPrometheusExporterMetricsEndpointV1 const resBody = await this.opts.connector.getPrometheusExporterMetrics(); res.status(200); res.send(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/get-transaction-receipt/get-transaction-receipt-by-txid-endpoint-v1.ts b/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/get-transaction-receipt/get-transaction-receipt-by-txid-endpoint-v1.ts index f6315ad3bdb..de9fea1bca8 100644 --- a/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/get-transaction-receipt/get-transaction-receipt-by-txid-endpoint-v1.ts +++ b/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/get-transaction-receipt/get-transaction-receipt-by-txid-endpoint-v1.ts @@ -93,11 +93,17 @@ export class GetTransactionReceiptByTxIDEndpointV1 ); res.status(200); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/plugin-ledger-connector-fabric.ts b/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/plugin-ledger-connector-fabric.ts index 8c4cc92f2e3..09737574350 100644 --- a/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/plugin-ledger-connector-fabric.ts +++ b/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/plugin-ledger-connector-fabric.ts @@ -108,6 +108,8 @@ import { getTransactionReceiptByTxID, IGetTransactionReceiptByTxIDOptions, } from "./common/get-transaction-receipt-by-tx-id"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; /** * Constant value holding the default $GOPATH in the Fabric CLI container as * observed on fabric deployments that are produced by the official examples @@ -1039,11 +1041,22 @@ export class PluginLedgerConnectorFabric JSON.stringify(transientMap[key]), ); } - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Building transient map crashed: `, ex); - throw new Error( - `${fnTag} Unable to build the transient map: ${ex.message}`, - ); + if (axios.isAxiosError(ex)) { + throw new Error( + `${fnTag} Unable to build the transient map: ${ + (ex as Error).message + }`, + ); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } const transactionProposal = await contract.createTransaction(fnName); @@ -1074,9 +1087,20 @@ export class PluginLedgerConnectorFabric this.prometheusExporter.addCurrentTransaction(); return res; - } catch (ex) { - this.log.error(`transact() crashed: `, ex); - throw new Error(`${fnTag} Unable to run transaction: ${ex.message}`); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`transact() crashed: `, ex); + throw new Error( + `${fnTag} Unable to run transaction: ${(ex as Error).message}`, + ); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } public async getTransactionReceiptByTxID( @@ -1110,9 +1134,18 @@ export class PluginLedgerConnectorFabric this.log.debug(`createCaClient() caName=%o caUrl=%o`, caName, caUrl); this.log.debug(`createCaClient() tlsOptions=%o`, tlsOptions); return new FabricCAServices(caUrl, tlsOptions, caName); - } catch (ex) { - this.log.error(`createCaClient() Failure:`, ex); - throw new Error(`${fnTag} Inner Exception: ${ex?.message}`); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`createCaClient() Failure:`, ex); + throw new Error(`${fnTag} Inner Exception: ${(ex as Error)?.message}`); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } @@ -1146,9 +1179,18 @@ export class PluginLedgerConnectorFabric await wallet.put(identityId, x509Identity); return [x509Identity, wallet]; - } catch (ex) { - this.log.error(`enrollAdmin() Failure:`, ex); - throw new Error(`${fnTag} Exception: ${ex?.message}`); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`enrollAdmin() Failure:`, ex); + throw new Error(`${fnTag} Exception: ${(ex as Error)?.message}`); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } /** diff --git a/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/run-transaction/run-transaction-endpoint-v1.ts b/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/run-transaction/run-transaction-endpoint-v1.ts index dcd016a6259..83d2d7ac5cf 100644 --- a/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/run-transaction/run-transaction-endpoint-v1.ts +++ b/packages/cactus-plugin-ledger-connector-fabric/src/main/typescript/run-transaction/run-transaction-endpoint-v1.ts @@ -88,11 +88,17 @@ export class RunTransactionEndpointV1 implements IWebServiceEndpoint { const resBody = await this.opts.connector.transact(reqBody); res.status(200); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/integration/identity-client.test.ts b/packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/integration/identity-client.test.ts index c51f0d9c0f2..f6294e0a7de 100644 --- a/packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/integration/identity-client.test.ts +++ b/packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/integration/identity-client.test.ts @@ -267,12 +267,14 @@ test("identity-clients", async (t: Test) => { try { await client.getPub(testNotFoundKey); t.fail("Should not get here"); - } catch (error) { - t.true( - (error as Error).message.includes( - `keyName = ${testNotFoundKey} not found`, - ), - ); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + t.true( + error.message.includes(`keyName = ${testNotFoundKey} not found`), + ); + } else { + t.fail("expected an axios error, got something else"); + } } } t.end(); diff --git a/packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/integration/openapi/openapi-validation-go.test.ts b/packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/integration/openapi/openapi-validation-go.test.ts index 1b173f66a7f..e34fc0b70a8 100644 --- a/packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/integration/openapi/openapi-validation-go.test.ts +++ b/packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/integration/openapi/openapi-validation-go.test.ts @@ -35,6 +35,7 @@ import { Configuration } from "@hyperledger/cactus-core-api"; import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core"; import OAS from "../../../../main/json/openapi.json"; +import axios from "axios"; const testCase = "check openapi validation in fabric endpoints"; const logLevel: LogLevelDesc = "TRACE"; @@ -269,19 +270,23 @@ test(testCase, async (t: Test) => { await apiClient.deployContractGoSourceV1( (parameters as any) as DeployContractGoSourceV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fDeployGo} without required targetPeerAddresses: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("targetPeerAddresses"), - "Rejected because targetPeerAddresses is required", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDeployGo} without required targetPeerAddresses: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("targetPeerAddresses"), + "Rejected because targetPeerAddresses is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -331,19 +336,23 @@ test(testCase, async (t: Test) => { await apiClient.deployContractGoSourceV1( (parameters as any) as DeployContractGoSourceV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fDeployGo} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDeployGo} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); diff --git a/packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/integration/openapi/openapi-validation.test.ts b/packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/integration/openapi/openapi-validation.test.ts index 7b287edef4d..5fb509e07a2 100644 --- a/packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/integration/openapi/openapi-validation.test.ts +++ b/packages/cactus-plugin-ledger-connector-fabric/src/test/typescript/integration/openapi/openapi-validation.test.ts @@ -34,6 +34,7 @@ import { Configuration } from "@hyperledger/cactus-core-api"; import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core"; import OAS from "../../../../main/json/openapi.json"; +import axios from "axios"; const testCase = "deploys Fabric 2.x contract from typescript source"; const logLevel: LogLevelDesc = "TRACE"; @@ -314,19 +315,23 @@ test(testCase, async (t: Test) => { await apiClient.deployContractV1( (parameters as any) as DeployContractV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fDeploy} without required channelId: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("channelId"), - "Rejected because channelId is required", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDeploy} without required channelId: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("channelId"), + "Rejected because channelId is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -353,19 +358,23 @@ test(testCase, async (t: Test) => { await apiClient.deployContractV1( (parameters as any) as DeployContractV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fDeploy} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDeploy} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -415,19 +424,23 @@ test(testCase, async (t: Test) => { await apiClient.runTransactionV1( (parameters as any) as RunTransactionRequest, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRun} without required contractName: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("contractName"), - "Rejected because contractName is required", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRun} without required contractName: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("contractName"), + "Rejected because contractName is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -454,19 +467,23 @@ test(testCase, async (t: Test) => { await apiClient.runTransactionV1( (parameters as any) as RunTransactionRequest, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRun} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRun} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); diff --git a/packages/cactus-plugin-ledger-connector-iroha/src/main/typescript/plugin-ledger-connector-iroha.ts b/packages/cactus-plugin-ledger-connector-iroha/src/main/typescript/plugin-ledger-connector-iroha.ts index df19e76c16e..1e49d6321db 100644 --- a/packages/cactus-plugin-ledger-connector-iroha/src/main/typescript/plugin-ledger-connector-iroha.ts +++ b/packages/cactus-plugin-ledger-connector-iroha/src/main/typescript/plugin-ledger-connector-iroha.ts @@ -240,8 +240,8 @@ export class PluginLedgerConnectorIroha publicKey: req.params[2], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.SetAccountDetail: { @@ -252,8 +252,8 @@ export class PluginLedgerConnectorIroha value: req.params[2], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.CompareAndSetAccountDetail: { @@ -268,8 +268,8 @@ export class PluginLedgerConnectorIroha }, ); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.CreateAsset: { @@ -281,8 +281,8 @@ export class PluginLedgerConnectorIroha precision: req.params[2], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.CreateDomain: { @@ -292,8 +292,8 @@ export class PluginLedgerConnectorIroha defaultRole: req.params[1], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.SetAccountQuorum: { @@ -303,8 +303,8 @@ export class PluginLedgerConnectorIroha quorum: req.params[1], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.AddAssetQuantity: { @@ -314,8 +314,8 @@ export class PluginLedgerConnectorIroha amount: req.params[1], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.SubtractAssetQuantity: { @@ -328,8 +328,8 @@ export class PluginLedgerConnectorIroha }, ); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.TransferAsset: { @@ -342,8 +342,8 @@ export class PluginLedgerConnectorIroha amount: req.params[4], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaQuery.GetSignatories: { @@ -352,8 +352,8 @@ export class PluginLedgerConnectorIroha accountId: req.params[0], }); return { transactionReceipt: queryRes }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaQuery.GetAccount: { @@ -362,8 +362,8 @@ export class PluginLedgerConnectorIroha accountId: req.params[0], }); return { transactionReceipt: queryRes }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaQuery.GetAccountDetail: { @@ -377,8 +377,8 @@ export class PluginLedgerConnectorIroha paginationWriter: req.params[5], }); return { transactionReceipt: queryRes }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaQuery.GetAssetInfo: { @@ -387,8 +387,8 @@ export class PluginLedgerConnectorIroha assetId: req.params[0], }); return { transactionReceipt: queryRes }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaQuery.GetAccountAssets: { @@ -399,8 +399,8 @@ export class PluginLedgerConnectorIroha firstAssetId: req.params[2], }); return { transactionReceipt: queryRes }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.AddSignatory: { @@ -410,8 +410,8 @@ export class PluginLedgerConnectorIroha publicKey: req.params[1], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.RemoveSignatory: { @@ -421,16 +421,16 @@ export class PluginLedgerConnectorIroha publicKey: req.params[1], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaQuery.GetRoles: { try { const response = await queries.getRoles(queryOptions); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.CreateRole: { @@ -440,8 +440,8 @@ export class PluginLedgerConnectorIroha permissionsList: req.params[1], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.AppendRole: { @@ -451,8 +451,8 @@ export class PluginLedgerConnectorIroha roleName: req.params[1], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.DetachRole: { @@ -462,8 +462,8 @@ export class PluginLedgerConnectorIroha roleName: req.params[1], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaQuery.GetRolePermissions: { @@ -472,8 +472,8 @@ export class PluginLedgerConnectorIroha roleId: req.params[0], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.GrantPermission: { @@ -484,8 +484,8 @@ export class PluginLedgerConnectorIroha permission: GrantablePermission[req.params[1] as permission], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.RevokePermission: { @@ -496,8 +496,8 @@ export class PluginLedgerConnectorIroha permission: GrantablePermission[req.params[1] as permission], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.SetSettingValue: { @@ -509,8 +509,8 @@ export class PluginLedgerConnectorIroha txHashesList: req.params[0], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaQuery.GetPendingTransactions: { @@ -520,8 +520,8 @@ export class PluginLedgerConnectorIroha firstTxHash: req.params[1], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaQuery.GetAccountTransactions: { @@ -532,8 +532,8 @@ export class PluginLedgerConnectorIroha firstTxHash: req.params[2], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaQuery.GetAccountAssetTransactions: { @@ -548,8 +548,8 @@ export class PluginLedgerConnectorIroha }, ); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaQuery.GetBlock: { @@ -558,8 +558,8 @@ export class PluginLedgerConnectorIroha height: req.params[0], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.CallEngine: { @@ -571,8 +571,8 @@ export class PluginLedgerConnectorIroha input: req.params[3], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaQuery.GetEngineReceipts: { @@ -581,16 +581,16 @@ export class PluginLedgerConnectorIroha txHash: req.params[0], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaQuery.FetchCommits: { try { const response = await queries.fetchCommits(queryOptions); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.AddPeer: { @@ -600,8 +600,8 @@ export class PluginLedgerConnectorIroha peerKey: req.params[1], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaCommand.RemovePeer: { @@ -610,16 +610,16 @@ export class PluginLedgerConnectorIroha publicKey: req.params[0], }); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } case IrohaQuery.GetPeers: { try { const response = await queries.getPeers(queryOptions); return { transactionReceipt: response }; - } catch (err) { - throw new RuntimeError(err); + } catch (err: unknown) { + throw new RuntimeError(JSON.stringify(err)); } } default: { diff --git a/packages/cactus-plugin-ledger-connector-iroha/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts b/packages/cactus-plugin-ledger-connector-iroha/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts index f1cbeb82661..07a3da553a5 100644 --- a/packages/cactus-plugin-ledger-connector-iroha/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts +++ b/packages/cactus-plugin-ledger-connector-iroha/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts @@ -84,11 +84,17 @@ export class GetPrometheusExporterMetricsEndpointV1 const resBody = await this.options.connector.getPrometheusExporterMetrics(); res.status(200); res.send(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-iroha/src/main/typescript/web-services/run-transaction-endpoint.ts b/packages/cactus-plugin-ledger-connector-iroha/src/main/typescript/web-services/run-transaction-endpoint.ts index 53519852c42..dde49d10076 100644 --- a/packages/cactus-plugin-ledger-connector-iroha/src/main/typescript/web-services/run-transaction-endpoint.ts +++ b/packages/cactus-plugin-ledger-connector-iroha/src/main/typescript/web-services/run-transaction-endpoint.ts @@ -91,29 +91,32 @@ export class RunTransactionEndpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.transact(reqBody); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { if (ex instanceof Http405NotAllowedError) { this.log.debug("Sending back HTTP405 Method Not Allowed error."); res.status(405); res.json(ex); return; + } else if ( + ex instanceof Error && + ex.message.includes("Error: Command response error") + ) { + this.log.debug("Sending back HTTP400 Bad Request error."); + res.status(400); + res.json(ex); + return; + } else { + this.log.error(`Crash while serving ${reqTag}`, ex); + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); } /** * An example output of the error message looks like: * "Error: Error: Command response error: expected=COMMITTED, actual=REJECTED" * @see https://iroha.readthedocs.io/en/main/develop/api/commands.html?highlight=CallEngine#id18 */ - if (ex.message.includes("Error: Command response error")) { - this.log.debug("Sending back HTTP400 Bad Request error."); - res.status(400); - res.json(ex); - return; - } - this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); } } } diff --git a/packages/cactus-plugin-ledger-connector-iroha/src/test/typescript/integration/openapi/openapi-validation.test.ts b/packages/cactus-plugin-ledger-connector-iroha/src/test/typescript/integration/openapi/openapi-validation.test.ts index 83178c7f314..89be717d8d8 100644 --- a/packages/cactus-plugin-ledger-connector-iroha/src/test/typescript/integration/openapi/openapi-validation.test.ts +++ b/packages/cactus-plugin-ledger-connector-iroha/src/test/typescript/integration/openapi/openapi-validation.test.ts @@ -38,6 +38,7 @@ import cryptoHelper from "iroha-helpers-ts/lib/cryptoHelper"; import OAS from "../../../../main/json/openapi.json"; import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core"; +import axios from "axios"; const testCase = "Iroha plugin openapi validation"; const logLevel: LogLevelDesc = "INFO"; @@ -174,16 +175,20 @@ test(testCase, async (t: Test) => { await apiClient.runTransactionV1( (parameters as any) as RunTransactionRequestV1, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRun} without required params: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("params"), "Rejected because params is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRun} without required params: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("params"), "Rejected because params is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); @@ -207,19 +212,23 @@ test(testCase, async (t: Test) => { await apiClient.runTransactionV1( (parameters as any) as RunTransactionRequestV1, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRun} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRun} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); }); diff --git a/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/plugin-ledger-connector-quorum.ts b/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/plugin-ledger-connector-quorum.ts index 3c80035f685..34c990f5442 100644 --- a/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/plugin-ledger-connector-quorum.ts +++ b/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/plugin-ledger-connector-quorum.ts @@ -62,6 +62,8 @@ import { GetPrometheusExporterMetricsEndpointV1, IGetPrometheusExporterMetricsEndpointV1Options, } from "./web-services/get-prometheus-exporter-metrics-endpoint-v1"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; export interface IPluginLedgerConnectorQuorumOptions extends ICactusPluginOptions { @@ -415,11 +417,20 @@ export class PluginLedgerConnectorQuorum const txHash = await sendTransaction(transactionConfig, secret); const transactionReceipt = await this.pollForTxReceipt(txHash); return { transactionReceipt }; - } catch (ex) { - throw new Error( - `${fnTag} Failed to invoke web3.eth.personal.sendTransaction(). ` + - `InnerException: ${ex.stack}`, - ); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + throw new Error( + `${fnTag} Failed to invoke web3.eth.personal.sendTransaction(). ` + + `InnerException: ${ex.stack}`, + ); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } diff --git a/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint-json-object.ts b/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint-json-object.ts index 9b0e72c7d54..ffe36c3052d 100644 --- a/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint-json-object.ts +++ b/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint-json-object.ts @@ -19,6 +19,8 @@ import { registerWebServiceEndpoint } from "@hyperledger/cactus-core"; import { PluginLedgerConnectorQuorum } from "../plugin-ledger-connector-quorum"; import { DeployContractSolidityBytecodeJsonObjectV1Request } from "../generated/openapi/typescript-axios"; import OAS from "../../json/openapi.json"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; export interface IDeployContractSolidityBytecodeOptionsJsonObject { logLevel?: LogLevelDesc; @@ -98,12 +100,21 @@ export class DeployContractSolidityBytecodeJsonObjectEndpoint reqBody, ); res.json(resBody); - } catch (ex) { - this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`Crash while serving ${reqTag}`, ex); + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint.ts b/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint.ts index 14d348fffb8..d9729987271 100644 --- a/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint.ts +++ b/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint.ts @@ -91,12 +91,19 @@ export class DeployContractSolidityBytecodeEndpoint try { const resBody = await this.options.connector.deployContract(reqBody); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts b/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts index 88b1eca0348..fcae27f01b8 100644 --- a/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts +++ b/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts @@ -90,11 +90,17 @@ export class GetPrometheusExporterMetricsEndpointV1 const resBody = await this.options.connector.getPrometheusExporterMetrics(); res.status(200); res.send(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/invoke-contract-endpoint-json-object.ts b/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/invoke-contract-endpoint-json-object.ts index 00af8359ff4..aa34cfa6d8b 100644 --- a/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/invoke-contract-endpoint-json-object.ts +++ b/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/invoke-contract-endpoint-json-object.ts @@ -17,6 +17,8 @@ import { registerWebServiceEndpoint } from "@hyperledger/cactus-core"; import { PluginLedgerConnectorQuorum } from "../plugin-ledger-connector-quorum"; import OAS from "../../json/openapi.json"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; export interface IInvokeContractEndpointJsonObjectOptions { logLevel?: LogLevelDesc; @@ -92,12 +94,21 @@ export class InvokeContractJsonObjectEndpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.getContractInfo(reqBody); res.json(resBody); - } catch (ex) { - this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`Crash while serving ${reqTag}`, ex); + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/invoke-contract-endpoint.ts b/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/invoke-contract-endpoint.ts index a15ea9a8ef6..8906757ae3e 100644 --- a/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/invoke-contract-endpoint.ts +++ b/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/invoke-contract-endpoint.ts @@ -90,12 +90,19 @@ export class InvokeContractEndpoint implements IWebServiceEndpoint { reqBody, ); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/run-transaction-endpoint.ts b/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/run-transaction-endpoint.ts index b26134087a8..fd4d23105cc 100644 --- a/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/run-transaction-endpoint.ts +++ b/packages/cactus-plugin-ledger-connector-quorum/src/main/typescript/web-services/run-transaction-endpoint.ts @@ -88,12 +88,19 @@ export class RunTransactionEndpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.transact(reqBody); res.json({ success: true, data: resBody }); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-quorum/src/test/typescript/integration/plugin-ledger-connector-quorum/deploy-contract/openapi/openapi-validation-no-keychain.test.ts b/packages/cactus-plugin-ledger-connector-quorum/src/test/typescript/integration/plugin-ledger-connector-quorum/deploy-contract/openapi/openapi-validation-no-keychain.test.ts index 0e4eedfd04b..3abfa944fb0 100644 --- a/packages/cactus-plugin-ledger-connector-quorum/src/test/typescript/integration/plugin-ledger-connector-quorum/deploy-contract/openapi/openapi-validation-no-keychain.test.ts +++ b/packages/cactus-plugin-ledger-connector-quorum/src/test/typescript/integration/plugin-ledger-connector-quorum/deploy-contract/openapi/openapi-validation-no-keychain.test.ts @@ -35,6 +35,7 @@ import { PluginRegistry } from "@hyperledger/cactus-core"; import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core"; import OAS from "../../../../../../main/json/openapi.json"; +import axios from "axios"; const logLevel: LogLevelDesc = "INFO"; @@ -186,20 +187,24 @@ test(testCase, async (t: Test) => { await apiClient.deployContractSolBytecodeJsonObjectV1( (parameters as any) as DeployContractSolidityBytecodeJsonObjectV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fDeploy} without required contractJSON and bytecode: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("contractJSON"), - "Rejected because contractJSON is required", - ); - t2.notOk(fields.includes("gas"), "gas is not required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDeploy} without required contractJSON and bytecode: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("contractJSON"), + "Rejected because contractJSON is required", + ); + t2.notOk(fields.includes("gas"), "gas is not required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -222,19 +227,23 @@ test(testCase, async (t: Test) => { await apiClient.deployContractSolBytecodeJsonObjectV1( (parameters as any) as DeployContractSolidityBytecodeJsonObjectV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fDeploy} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDeploy} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -258,20 +267,24 @@ test(testCase, async (t: Test) => { await apiClient.invokeContractV1NoKeychain( (parameters as any) as InvokeContractJsonObjectV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fInvoke} without required contractJSON and methodName: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("contractJSON"), - "Rejected because contractJSON is required", - ); - t2.notOk(fields.includes("nonce"), "nonce is not required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fInvoke} without required contractJSON and methodName: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("contractJSON"), + "Rejected because contractJSON is required", + ); + t2.notOk(fields.includes("nonce"), "nonce is not required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -297,19 +310,23 @@ test(testCase, async (t: Test) => { await apiClient.invokeContractV1NoKeychain( (parameters as any) as InvokeContractJsonObjectV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fInvoke} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fInvoke} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); diff --git a/packages/cactus-plugin-ledger-connector-quorum/src/test/typescript/integration/plugin-ledger-connector-quorum/deploy-contract/openapi/openapi-validation.test.ts b/packages/cactus-plugin-ledger-connector-quorum/src/test/typescript/integration/plugin-ledger-connector-quorum/deploy-contract/openapi/openapi-validation.test.ts index 4a20ee4cc1d..2f2af32643d 100644 --- a/packages/cactus-plugin-ledger-connector-quorum/src/test/typescript/integration/plugin-ledger-connector-quorum/deploy-contract/openapi/openapi-validation.test.ts +++ b/packages/cactus-plugin-ledger-connector-quorum/src/test/typescript/integration/plugin-ledger-connector-quorum/deploy-contract/openapi/openapi-validation.test.ts @@ -31,6 +31,7 @@ import { Configuration } from "@hyperledger/cactus-core-api"; import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core"; import OAS from "../../../../../../main/json/openapi.json"; +import axios from "axios"; const logLevel: LogLevelDesc = "INFO"; const testCase = "Quorum API"; @@ -174,20 +175,24 @@ test(testCase, async (t: Test) => { await apiClient.deployContractSolBytecodeV1( parameters as DeployContractSolidityBytecodeV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fDeploy} without required contractName and bytecode: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("contractName"), - "Rejected because contractName is required", - ); - t2.notOk(fields.includes("gas"), "gas is not required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDeploy} without required contractName and bytecode: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("contractName"), + "Rejected because contractName is required", + ); + t2.notOk(fields.includes("gas"), "gas is not required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -209,19 +214,23 @@ test(testCase, async (t: Test) => { await apiClient.deployContractSolBytecodeV1( parameters as DeployContractSolidityBytecodeV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fDeploy} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDeploy} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -270,20 +279,24 @@ test(testCase, async (t: Test) => { }, }; await apiClient.invokeContractV1(parameters as InvokeContractV1Request); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fInvoke} without required methodName: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("methodName"), - "Rejected because methodName is required", - ); - t2.notOk(fields.includes("nonce"), "nonce is not required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fInvoke} without required methodName: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("methodName"), + "Rejected because methodName is required", + ); + t2.notOk(fields.includes("nonce"), "nonce is not required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -308,19 +321,23 @@ test(testCase, async (t: Test) => { fake: 4, }; await apiClient.invokeContractV1(parameters as InvokeContractV1Request); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fInvoke} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fInvoke} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -359,20 +376,24 @@ test(testCase, async (t: Test) => { }, }; await apiClient.runTransactionV1(parameters as RunTransactionRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRun} without required transactionConfig: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("transactionConfig"), - "Rejected because transactionConfig is required", - ); - t2.notOk(fields.includes("timeoutMs"), "timeoutMs is not required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRun} without required transactionConfig: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("transactionConfig"), + "Rejected because transactionConfig is required", + ); + t2.notOk(fields.includes("timeoutMs"), "timeoutMs is not required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -394,19 +415,23 @@ test(testCase, async (t: Test) => { fake: 4, }; await apiClient.runTransactionV1(parameters as RunTransactionRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRun} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRun} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); diff --git a/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint.ts b/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint.ts index 70e94a8f392..4f0d972dcce 100644 --- a/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint.ts +++ b/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/deploy-contract-solidity-bytecode-endpoint.ts @@ -91,12 +91,19 @@ export class DeployContractSolidityBytecodeEndpoint try { const resBody = await this.options.connector.deployContract(reqBody); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts b/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts index ccac3b7803e..65e68995a9b 100644 --- a/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts +++ b/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/get-prometheus-exporter-metrics-endpoint-v1.ts @@ -90,11 +90,17 @@ export class GetPrometheusExporterMetricsEndpointV1 const resBody = await this.options.connector.getPrometheusExporterMetrics(); res.status(200); res.send(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`${fnTag} failed to serve request`, ex); - res.status(500); - res.statusMessage = ex.message; - res.json({ error: ex.stack }); + if (ex instanceof Error) { + res.status(500); + res.statusMessage = ex.message; + res.json({ error: ex.stack }); + } else { + res.status(500); + res.statusMessage = JSON.stringify(ex); + res.json({ error: JSON.stringify(ex) }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/invoke-contract-endpoint.ts b/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/invoke-contract-endpoint.ts index ef93f648d34..734af01229e 100644 --- a/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/invoke-contract-endpoint.ts +++ b/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/invoke-contract-endpoint.ts @@ -88,12 +88,19 @@ export class InvokeContractEndpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.invokeContract(reqBody); res.json(resBody); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/run-transaction-endpoint.ts b/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/run-transaction-endpoint.ts index d25d2e35fea..96bc7d6669d 100644 --- a/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/run-transaction-endpoint.ts +++ b/packages/cactus-plugin-ledger-connector-xdai/src/main/typescript/web-services/run-transaction-endpoint.ts @@ -88,12 +88,19 @@ export class RunTransactionEndpoint implements IWebServiceEndpoint { try { const resBody = await this.options.connector.transact(reqBody); res.json({ success: true, data: resBody }); - } catch (ex) { + } catch (ex: unknown) { this.log.error(`Crash while serving ${reqTag}`, ex); - res.status(500).json({ - message: "Internal Server Error", - error: ex?.stack || ex?.message, - }); + if (ex instanceof Error) { + res.status(500).json({ + message: "Internal Server Error", + error: ex.stack || ex.message, + }); + } else { + res.status(500).json({ + message: "Internal Server Error", + error: JSON.stringify(ex), + }); + } } } } diff --git a/packages/cactus-plugin-ledger-connector-xdai/src/test/typescript/integration/openapi/openapi-validation.test.ts b/packages/cactus-plugin-ledger-connector-xdai/src/test/typescript/integration/openapi/openapi-validation.test.ts index 4bd1c5c5f03..5dd47d7166f 100644 --- a/packages/cactus-plugin-ledger-connector-xdai/src/test/typescript/integration/openapi/openapi-validation.test.ts +++ b/packages/cactus-plugin-ledger-connector-xdai/src/test/typescript/integration/openapi/openapi-validation.test.ts @@ -33,6 +33,7 @@ import { import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core"; import OAS from "../../../../main/json/openapi.json"; +import axios from "axios"; const testCase = "xDai API"; const logLevel: LogLevelDesc = "TRACE"; @@ -169,19 +170,23 @@ test(testCase, async (t: Test) => { await apiClient.deployContractV1( (parameters as any) as DeployContractV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fDeploy} without required keychainId: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("keychainId"), - "Rejected because keychainId is required", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDeploy} without required keychainId: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("keychainId"), + "Rejected because keychainId is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -206,19 +211,23 @@ test(testCase, async (t: Test) => { await apiClient.deployContractV1( (parameters as any) as DeployContractV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fDeploy} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fDeploy} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -265,19 +274,23 @@ test(testCase, async (t: Test) => { await apiClient.invokeContractV1( (parameters as any) as InvokeContractV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fInvoke} without required contractName: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("contractName"), - "Rejected because contractName is required", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fInvoke} without required contractName: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("contractName"), + "Rejected because contractName is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -301,19 +314,23 @@ test(testCase, async (t: Test) => { await apiClient.invokeContractV1( (parameters as any) as InvokeContractV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fInvoke} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fInvoke} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -364,19 +381,23 @@ test(testCase, async (t: Test) => { await apiClient.runTransactionV1( (parameters as any) as RunTransactionV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRun} without required consistencyStrategy: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("consistencyStrategy"), - "Rejected because consistencyStrategy is required", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRun} without required consistencyStrategy: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("consistencyStrategy"), + "Rejected because consistencyStrategy is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -406,19 +427,23 @@ test(testCase, async (t: Test) => { await apiClient.runTransactionV1( (parameters as any) as RunTransactionV1Request, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRun} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRun} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); diff --git a/packages/cactus-test-plugin-consortium-manual/src/test/typescript/integration/plugin-consortium-manual/openapi/openapi-validation.test.ts b/packages/cactus-test-plugin-consortium-manual/src/test/typescript/integration/plugin-consortium-manual/openapi/openapi-validation.test.ts index 88d76570610..e9578da55ec 100644 --- a/packages/cactus-test-plugin-consortium-manual/src/test/typescript/integration/plugin-consortium-manual/openapi/openapi-validation.test.ts +++ b/packages/cactus-test-plugin-consortium-manual/src/test/typescript/integration/plugin-consortium-manual/openapi/openapi-validation.test.ts @@ -23,6 +23,7 @@ import { ConsortiumMember, } from "@hyperledger/cactus-core-api"; import { PluginRegistry } from "@hyperledger/cactus-core"; +import axios from "axios"; const testCase = "cactus-plugin-consortium-manual API"; @@ -281,19 +282,23 @@ test(testCase, async (t: Test) => { const api = new DefaultApi(configuration); try { await api.getNodeJwsV1({ fake: 4 }); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fGetNodeJwt} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fGetNodeJwt} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -304,19 +309,23 @@ test(testCase, async (t: Test) => { const api = new DefaultApi(configuration); try { await api.getConsortiumJwsV1({ fake: 4 }); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fGetConsortiumJws} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fGetConsortiumJws} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); diff --git a/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/initialize-endpoint.test.ts b/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/initialize-endpoint.test.ts index a3531f34bf2..6f7702b3123 100644 --- a/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/initialize-endpoint.test.ts +++ b/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/initialize-endpoint.test.ts @@ -31,6 +31,7 @@ import { import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; import HashTimeLockJSON from "../../../../../../cactus-plugin-htlc-eth-besu-erc20/src/main/solidity/contracts/HashedTimeLockContract.json"; +import axios from "axios"; const logLevel: LogLevelDesc = "INFO"; const estimatedGas = 6721975; @@ -234,8 +235,12 @@ test("Test initialize function with invalid params", async (t: Test) => { try { const res = await api.initializeV1(request); t.equal(res.status, 400, "response status is 400"); - } catch (error) { - t.equal(error.response.status, 400, "response status is 400"); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + t.equal(error.response?.status, 400, "response status is 400"); + } else { + t.fail("expected an axios error, got something else"); + } } t.end(); }); diff --git a/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/new-contract-endpoint.test.ts b/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/new-contract-endpoint.test.ts index dfde2bb4c37..069e2604765 100644 --- a/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/new-contract-endpoint.test.ts +++ b/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/new-contract-endpoint.test.ts @@ -33,6 +33,7 @@ import { import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; import HashTimeLockJSON from "../../../../../../cactus-plugin-htlc-eth-besu-erc20/src/main/solidity/contracts/HashedTimeLockContract.json"; import TestTokenJSON from "../../../solidity/token-erc20-contract/Test_Token.json"; +import axios from "axios"; const logLevel: LogLevelDesc = "INFO"; const estimatedGas = 6721975; @@ -402,8 +403,12 @@ test("Test new invalid contract with 0 inputAmount token for HTLC", async (t: Te }; const res = await api.newContractV1(request); t.equal(res.status, 400, "response status is 400"); - } catch (error) { - t.equal(error.response.status, 400, "response status is 400"); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + t.equal(error.response?.status, 400, "response status is 400"); + } else { + t.fail("expected an axios error, got something else"); + } } t.end(); }); diff --git a/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/openapi/openapi-validation.test.ts b/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/openapi/openapi-validation.test.ts index 3eb7943809b..fede43af02a 100644 --- a/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/openapi/openapi-validation.test.ts +++ b/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/openapi/openapi-validation.test.ts @@ -41,6 +41,7 @@ import HashTimeLockJSON from "../../../../../../../cactus-plugin-htlc-eth-besu-e import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core"; import { PluginHtlcEthBesuErc20 } from "@hyperledger/cactus-plugin-htlc-eth-besu-erc20"; +import axios from "axios"; const connectorId = uuidv4(); const logLevel: LogLevelDesc = "INFO"; @@ -214,19 +215,23 @@ test(testCase, async (t: Test) => { try { await api.initializeV1((parameters as any) as InitializeRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fInitialize} without required connectorId: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("connectorId"), - "Rejected because connectorId is required", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fInitialize} without required connectorId: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("connectorId"), + "Rejected because connectorId is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -244,19 +249,23 @@ test(testCase, async (t: Test) => { try { await api.initializeV1((parameters as any) as InitializeRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fInitialize} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fInitialize} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -358,19 +367,23 @@ test(testCase, async (t: Test) => { }; try { await api.newContractV1((parameters as any) as NewContractRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fNew} without required contractAddress: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("contractAddress"), - "Rejected because contractAddress is required", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fNew} without required contractAddress: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("contractAddress"), + "Rejected because contractAddress is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -395,19 +408,23 @@ test(testCase, async (t: Test) => { }; try { await api.newContractV1((parameters as any) as NewContractRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fNew} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fNew} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -459,16 +476,20 @@ test(testCase, async (t: Test) => { }; try { await api.refundV1((parameters as any) as RefundRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRefund} without required id: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("id"), "Rejected because id is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRefund} without required id: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("id"), "Rejected because id is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -484,19 +505,23 @@ test(testCase, async (t: Test) => { }; try { await api.refundV1((parameters as any) as RefundRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRefund} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRefund} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -601,16 +626,20 @@ test(testCase, async (t: Test) => { try { await api.withdrawV1((parameters as any) as WithdrawRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fWithdraw} without required id: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("id"), "Rejected because id is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fWithdraw} without required id: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("id"), "Rejected because id is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -628,19 +657,23 @@ test(testCase, async (t: Test) => { try { await api.withdrawV1((parameters as any) as WithdrawRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fWithdraw} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fWithdraw} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -675,16 +708,20 @@ test(testCase, async (t: Test) => { try { await api.getStatusV1((parameters as any) as GetStatusRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fStatus} without required id: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("ids"), "Rejected because ids is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fStatus} without required id: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("ids"), "Rejected because ids is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -701,19 +738,23 @@ test(testCase, async (t: Test) => { try { await api.getStatusV1((parameters as any) as GetStatusRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fStatus} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fStatus} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -748,16 +789,20 @@ test(testCase, async (t: Test) => { await api.getSingleStatusV1( (parameters as any) as GetSingleStatusRequest, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fSingleStatus} without required id: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("id"), "Rejected because id is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fSingleStatus} without required id: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("id"), "Rejected because id is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -775,19 +820,23 @@ test(testCase, async (t: Test) => { try { // eslint-disable-next-line prettier/prettier await api.getSingleStatusV1((parameters as any) as GetSingleStatusRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fSingleStatus} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fSingleStatus} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); diff --git a/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/refund-endpoint.test.ts b/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/refund-endpoint.test.ts index 9be571c2a83..eb2afae5bfc 100644 --- a/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/refund-endpoint.test.ts +++ b/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/refund-endpoint.test.ts @@ -36,6 +36,7 @@ import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory import TestTokenJSON from "../../../solidity/token-erc20-contract/Test_Token.json"; import DemoHelperJSON from "../../../solidity/token-erc20-contract/DemoHelpers.json"; import HashTimeLockJSON from "../../../../../../cactus-plugin-htlc-eth-besu-erc20/src/main/solidity/contracts/HashedTimeLockContract.json"; +import axios from "axios"; const logLevel: LogLevelDesc = "INFO"; const estimatedGas = 6721975; @@ -584,8 +585,12 @@ test("Test invalid refund with invalid time", async (t: Test) => { }; const resRefund = await api.refundV1(refundRequest); t.equal(resRefund.status, 400, "response status is 400"); - } catch (error) { - t.equal(error.response.status, 400, "response status is 400"); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + t.equal(error.response?.status, 400, "response status is 400"); + } else { + t.fail("expected an axios error, got something else"); + } } t.comment("Get balance of account"); diff --git a/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/withdraw-endpoint.test.ts b/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/withdraw-endpoint.test.ts index 55be3aff346..84018972a45 100644 --- a/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/withdraw-endpoint.test.ts +++ b/packages/cactus-test-plugin-htlc-eth-besu-erc20/src/test/typescript/integration/plugin-htlc-eth-besu-erc20/withdraw-endpoint.test.ts @@ -37,6 +37,7 @@ import DemoHelperJSON from "../../../solidity/token-erc20-contract/DemoHelpers.j import HashTimeLockJSON from "../../../../../../cactus-plugin-htlc-eth-besu-erc20/src/main/solidity/contracts/HashedTimeLockContract.json"; import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; +import axios from "axios"; const logLevel: LogLevelDesc = "INFO"; const estimatedGas = 6721975; @@ -503,8 +504,12 @@ test("Test invalid withdraw with invalid id", async (t: Test) => { }; const resWithdraw = await api.withdrawV1(withdrawRequest); t.equal(resWithdraw.status, 400, "response status is 400"); - } catch (error) { - t.equal(error.response.status, 400, "response status is 400"); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + t.equal(error.response?.status, 400, "response status is 400"); + } else { + t.fail("expected an axios error, got something else"); + } } t.comment("Get balance of receiver account"); const responseFinalBalance = await connector.invokeContract({ diff --git a/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/get-single-status-endpoint-invalid.test.ts b/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/get-single-status-endpoint-invalid.test.ts index 91d45510b4a..68db7833100 100644 --- a/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/get-single-status-endpoint-invalid.test.ts +++ b/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/get-single-status-endpoint-invalid.test.ts @@ -34,6 +34,7 @@ import { } from "@hyperledger/cactus-test-tooling"; import { DataTest } from "../data-test"; import DemoHelperJSON from "../../../solidity/contracts/DemoHelpers.json"; +import axios from "axios"; const connectorId = uuidv4(); const logLevel: LogLevelDesc = "INFO"; @@ -217,8 +218,12 @@ test(testCase, async (t: Test) => { keychainId: "", }); t.equal(res.status, 500, "response status is 500"); - } catch (e) { - t.equal(e.response.status, 500); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t.equal(e.response?.status, 500); + } else { + t.fail("expected an axios error, got something else"); + } } t.end(); }); diff --git a/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/get-status-endpoint-invalid.test.ts b/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/get-status-endpoint-invalid.test.ts index be16e15df40..24ea935a0ea 100644 --- a/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/get-status-endpoint-invalid.test.ts +++ b/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/get-status-endpoint-invalid.test.ts @@ -35,6 +35,7 @@ import { import { DataTest } from "../data-test"; import DemoHelperJSON from "../../../solidity/contracts/DemoHelpers.json"; import HashTimeLockJSON from "../../../../../../cactus-plugin-htlc-eth-besu/src/main/solidity/contracts/HashTimeLock.json"; +import axios from "axios"; const connectorId = uuidv4(); const logLevel: LogLevelDesc = "INFO"; @@ -228,8 +229,12 @@ test(testCase, async (t: Test) => { keychainId: "", }); t.equal(res.status, 500, "response status is 500"); - } catch (e) { - t.equal(e.response.status, 500); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t.equal(e.response?.status, 500); + } else { + t.fail("expected an axios error, got something else"); + } } t.end(); }); diff --git a/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/initialize-endpoint-invalid.test.ts b/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/initialize-endpoint-invalid.test.ts index 69bfae24c89..fd7c1c68dca 100644 --- a/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/initialize-endpoint-invalid.test.ts +++ b/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/initialize-endpoint-invalid.test.ts @@ -30,6 +30,7 @@ import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory import { DataTest } from "../data-test"; import DemoHelperJSON from "../../../solidity/contracts/DemoHelpers.json"; import HashTimeLockJSON from "../../../../../../cactus-plugin-htlc-eth-besu/src/main/solidity/contracts/HashTimeLock.json"; +import axios from "axios"; const connectorId = uuidv4(); const logLevel: LogLevelDesc = "INFO"; @@ -140,8 +141,12 @@ test(testCase, async (t: Test) => { deployOut.transactionReceipt, "pluginHtlc.initialize() output.transactionReceipt is truthy OK", ); - } catch (error) { - t.ok(error, "pluginHtlc.initialize() error is truthy OK"); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + t.ok(error, "pluginHtlc.initialize() error is truthy OK"); + } else { + t.fail("expected an axios error, got something else"); + } } t.end(); }); diff --git a/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/new-contract-endpoint-invalid.test.ts b/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/new-contract-endpoint-invalid.test.ts index 91a4ed60680..40a72839ff0 100644 --- a/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/new-contract-endpoint-invalid.test.ts +++ b/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/new-contract-endpoint-invalid.test.ts @@ -34,6 +34,7 @@ import { import { DataTest } from "../data-test"; import DemoHelperJSON from "../../../solidity/contracts/DemoHelpers.json"; import HashTimeLockJSON from "../../../../../../cactus-plugin-htlc-eth-besu/src/main/solidity/contracts/HashTimeLock.json"; +import axios from "axios"; const connectorId = uuidv4(); const logLevel: LogLevelDesc = "INFO"; @@ -191,7 +192,11 @@ test(testCase, async (t: Test) => { t.ok(resp, "response newContract is OK"); t.equal(resp.status, 200, "response status newContract is OK"); } catch (error) { - t.equal(error.response.status, 500, "response status is 500"); + if (axios.isAxiosError(error)) { + t.equal(error.response?.status, 500, "response status is 500"); + } else { + t.fail("expected an axios error, got something else"); + } } t.end(); }); diff --git a/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/openapi/openapi-validation.test.ts b/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/openapi/openapi-validation.test.ts index f202d385b2f..91f53e31502 100644 --- a/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/openapi/openapi-validation.test.ts +++ b/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/openapi/openapi-validation.test.ts @@ -41,6 +41,7 @@ import HashTimeLockJSON from "../../../../../../../cactus-plugin-htlc-eth-besu/s import { installOpenapiValidationMiddleware } from "@hyperledger/cactus-core"; import { PluginHtlcEthBesu } from "@hyperledger/cactus-plugin-htlc-eth-besu"; +import axios from "axios"; const connectorId = uuidv4(); const logLevel: LogLevelDesc = "INFO"; @@ -202,19 +203,23 @@ test(testCase, async (t: Test) => { try { await api.initializeV1((parameters as any) as InitializeRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fInitialize} without required connectorId: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("connectorId"), - "Rejected because connectorId is required", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fInitialize} without required connectorId: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("connectorId"), + "Rejected because connectorId is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -232,19 +237,23 @@ test(testCase, async (t: Test) => { try { await api.initializeV1((parameters as any) as InitializeRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fInitialize} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fInitialize} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -311,19 +320,23 @@ test(testCase, async (t: Test) => { }; try { await api.newContractV1((parameters as any) as NewContractObj); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fNew} without required contractAddress: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("contractAddress"), - "Rejected because contractAddress is required", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fNew} without required contractAddress: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("contractAddress"), + "Rejected because contractAddress is required", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -347,19 +360,23 @@ test(testCase, async (t: Test) => { }; try { await api.newContractV1((parameters as any) as NewContractObj); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fNew} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fNew} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected axios error, got something else"); + } } t2.end(); @@ -410,16 +427,20 @@ test(testCase, async (t: Test) => { }; try { await api.refundV1((parameters as any) as RefundReq); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRefund} without required id: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("id"), "Rejected because id is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRefund} without required id: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("id"), "Rejected because id is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -435,19 +456,23 @@ test(testCase, async (t: Test) => { }; try { await api.refundV1((parameters as any) as RefundReq); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fRefund} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fRefund} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -516,16 +541,20 @@ test(testCase, async (t: Test) => { try { await api.withdrawV1((parameters as any) as WithdrawReq); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fWithdraw} without required id: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("id"), "Rejected because id is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fWithdraw} without required id: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("id"), "Rejected because id is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -544,19 +573,23 @@ test(testCase, async (t: Test) => { try { await api.withdrawV1((parameters as any) as WithdrawReq); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fWithdraw} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fWithdraw} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -633,16 +666,20 @@ test(testCase, async (t: Test) => { try { await api.getStatusV1((parameters as any) as GetStatusRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fStatus} without required ids: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("ids"), "Rejected because ids is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fStatus} without required ids: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("ids"), "Rejected because ids is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -659,19 +696,23 @@ test(testCase, async (t: Test) => { try { await api.getStatusV1((parameters as any) as GetStatusRequest); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fStatus} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fStatus} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -748,16 +789,20 @@ test(testCase, async (t: Test) => { await api.getSingleStatusV1( (parameters as any) as GetSingleStatusRequest, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fSingleStatus} without required id: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok(fields.includes("id"), "Rejected because id is required"); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fSingleStatus} without required id: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok(fields.includes("id"), "Rejected because id is required"); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); @@ -776,19 +821,23 @@ test(testCase, async (t: Test) => { await api.getSingleStatusV1( (parameters as any) as GetSingleStatusRequest, ); - } catch (e) { - t2.equal( - e.response.status, - 400, - `Endpoint ${fSingleStatus} with fake=4: response.status === 400 OK`, - ); - const fields = e.response.data.map((param: any) => - param.path.replace(".body.", ""), - ); - t2.ok( - fields.includes("fake"), - "Rejected because fake is not a valid parameter", - ); + } catch (e: unknown) { + if (axios.isAxiosError(e)) { + t2.equal( + e.response?.status, + 400, + `Endpoint ${fSingleStatus} with fake=4: response.status === 400 OK`, + ); + const fields = e.response?.data.map((param: any) => + param.path.replace(".body.", ""), + ); + t2.ok( + fields.includes("fake"), + "Rejected because fake is not a valid parameter", + ); + } else { + t2.fail("expected an axios error, got something else"); + } } t2.end(); diff --git a/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/refund-endpoint-invalid.test.ts b/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/refund-endpoint-invalid.test.ts index c0ac9dbca78..1391424c3b3 100644 --- a/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/refund-endpoint-invalid.test.ts +++ b/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/refund-endpoint-invalid.test.ts @@ -35,6 +35,7 @@ import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory import { DataTest } from "../data-test"; import DemoHelperJSON from "../../../solidity/contracts/DemoHelpers.json"; import HashTimeLockJSON from "../../../../../../cactus-plugin-htlc-eth-besu/src/main/solidity/contracts/HashTimeLock.json"; +import axios from "axios"; const connectorId = uuidv4(); const logLevel: LogLevelDesc = "INFO"; @@ -230,8 +231,12 @@ test(testCase, async (t: Test) => { }; const refundResponse = await api.refundV1(refundRequest); t.equal(refundResponse.status, 200); - } catch (error) { - t.equal(error.response.status, 500, "response status is 500"); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + t.equal(error.response?.status, 500, "response status is 500"); + } else { + t.fail("expected an axios error, got something else"); + } } t.end(); }); diff --git a/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/withdraw-endpoint-invalid.test.ts b/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/withdraw-endpoint-invalid.test.ts index f9f6720ff27..56251af415e 100644 --- a/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/withdraw-endpoint-invalid.test.ts +++ b/packages/cactus-test-plugin-htlc-eth-besu/src/test/typescript/integration/plugin-htlc-eth-besu/withdraw-endpoint-invalid.test.ts @@ -35,6 +35,7 @@ import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory import { DataTest } from "../data-test"; import DemoHelperJSON from "../../../solidity/contracts/DemoHelpers.json"; import HashTimeLockJSON from "../../../../../../cactus-plugin-htlc-eth-besu/src/main/solidity/contracts/HashTimeLock.json"; +import axios from "axios"; const connectorId = uuidv4(); const logLevel: LogLevelDesc = "INFO"; @@ -220,8 +221,12 @@ test(testCase, async (t: Test) => { const res = await api.withdrawV1(bodyWithdraw); t.equal(res.status, 200, "response status is 200 OK"); - } catch (error) { - t.equal(error.response.status, 500, "response status is 500"); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + t.equal(error.response?.status, 500, "response status is 500"); + } else { + t.fail("expected an axios error, got somethign else"); + } } t.end(); }); diff --git a/packages/cactus-test-plugin-ledger-connector-besu/src/test/typescript/integration/plugin-validator-besu/sign-transaction-endpoint.test.ts b/packages/cactus-test-plugin-ledger-connector-besu/src/test/typescript/integration/plugin-validator-besu/sign-transaction-endpoint.test.ts index 8fd57b4ff67..b4bb3d8f52f 100644 --- a/packages/cactus-test-plugin-ledger-connector-besu/src/test/typescript/integration/plugin-validator-besu/sign-transaction-endpoint.test.ts +++ b/packages/cactus-test-plugin-ledger-connector-besu/src/test/typescript/integration/plugin-validator-besu/sign-transaction-endpoint.test.ts @@ -36,6 +36,7 @@ import { import { PluginRegistry } from "@hyperledger/cactus-core"; import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; +import axios from "axios"; const testCase = "Test sign transaction endpoint"; const logLevel: LogLevelDesc = "TRACE"; @@ -185,12 +186,16 @@ test(testCase, async (t: Test) => { "0x46eac4d1d1ff81837698cbab38862a428ddf042f92855a72010de2771a7b704d", }; await api.signTransactionV1(notFoundRequest); - } catch (error) { - t.equal(error.response.status, 404, "HTTP response status are equal"); - t.equal( - error.response.statusText, - "Transaction not found", - "Response text are equal", - ); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + t.equal(error.response?.status, 404, "HTTP response status are equal"); + t.equal( + error.response?.statusText, + "Transaction not found", + "Response text are equal", + ); + } else { + t.fail("expected an axios error, got something else"); + } } }); diff --git a/packages/cactus-test-plugin-ledger-connector-besu/src/test/typescript/integration/plugin-validator-besu/v21-sign-transaction-endpoint.test.ts b/packages/cactus-test-plugin-ledger-connector-besu/src/test/typescript/integration/plugin-validator-besu/v21-sign-transaction-endpoint.test.ts index 81049557f65..361ec9bc370 100644 --- a/packages/cactus-test-plugin-ledger-connector-besu/src/test/typescript/integration/plugin-validator-besu/v21-sign-transaction-endpoint.test.ts +++ b/packages/cactus-test-plugin-ledger-connector-besu/src/test/typescript/integration/plugin-validator-besu/v21-sign-transaction-endpoint.test.ts @@ -36,6 +36,7 @@ import { import { PluginRegistry } from "@hyperledger/cactus-core"; import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; +import axios from "axios"; const testCase = "Test sign transaction endpoint"; const logLevel: LogLevelDesc = "TRACE"; @@ -188,12 +189,16 @@ test(testCase, async (t: Test) => { "0x46eac4d1d1ff81837698cbab38862a428ddf042f92855a72010de2771a7b704d", }; await api.signTransactionV1(notFoundRequest); - } catch (error) { - t.equal(error.response.status, 404, "HTTP response status are equal"); - t.equal( - error.response.statusText, - "Transaction not found", - "Response text are equal", - ); + } catch (error: unknown) { + if (axios.isAxiosError(error)) { + t.equal(error.response?.status, 404, "HTTP response status are equal"); + t.equal( + error.response?.statusText, + "Transaction not found", + "Response text are equal", + ); + } else { + t.fail("expected an axios error, got something else"); + } } }); diff --git a/packages/cactus-test-tooling/src/main/typescript/besu/besu-mp-test-ledger.ts b/packages/cactus-test-tooling/src/main/typescript/besu/besu-mp-test-ledger.ts index fc17aab2747..010ab115a40 100644 --- a/packages/cactus-test-tooling/src/main/typescript/besu/besu-mp-test-ledger.ts +++ b/packages/cactus-test-tooling/src/main/typescript/besu/besu-mp-test-ledger.ts @@ -11,6 +11,7 @@ import { LoggerProvider } from "@hyperledger/cactus-common"; import { Containers } from "../common/containers"; import { RuntimeError } from "run-time-error"; import { EventEmitter } from "events"; +import axios from "axios"; export interface IBesuMpTestLedgerOptions { readonly logLevel?: LogLevelDesc; @@ -160,9 +161,18 @@ export class BesuMpTestLedger { try { await Containers.waitForHealthCheck(this.containerId.get()); resolve(container); - } catch (ex) { - this.log.error(ex); - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(ex); + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); diff --git a/packages/cactus-test-tooling/src/main/typescript/besu/besu-test-ledger.ts b/packages/cactus-test-tooling/src/main/typescript/besu/besu-test-ledger.ts index cffa9f7e106..5d4a75ba4dc 100644 --- a/packages/cactus-test-tooling/src/main/typescript/besu/besu-test-ledger.ts +++ b/packages/cactus-test-tooling/src/main/typescript/besu/besu-test-ledger.ts @@ -15,6 +15,8 @@ import { ITestLedger } from "../i-test-ledger"; import { Streams } from "../common/streams"; import { IKeyPair } from "../i-key-pair"; import { Containers } from "../common/containers"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; export interface IBesuTestLedgerConstructorOptions { containerImageVersion?: string; @@ -278,8 +280,17 @@ export class BesuTestLedger implements ITestLedger { await this.waitForHealthCheck(); this.log.debug(`Healthcheck passing OK.`); resolve(container); - } catch (ex) { - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); diff --git a/packages/cactus-test-tooling/src/main/typescript/cactus-keychain-vault-server/cactus-keychain-vault-server.ts b/packages/cactus-test-tooling/src/main/typescript/cactus-keychain-vault-server/cactus-keychain-vault-server.ts index 5f6a5a61a86..e28bfd45cbf 100644 --- a/packages/cactus-test-tooling/src/main/typescript/cactus-keychain-vault-server/cactus-keychain-vault-server.ts +++ b/packages/cactus-test-tooling/src/main/typescript/cactus-keychain-vault-server/cactus-keychain-vault-server.ts @@ -10,6 +10,8 @@ import { } from "@hyperledger/cactus-common"; import { Containers } from "../common/containers"; +import { RuntimeError } from "run-time-error"; +import axios from "axios"; export interface ICactusKeychainVaultServerOptions { envVars?: string[]; @@ -102,8 +104,17 @@ export class CactusKeychainVaultServer { try { await Containers.waitForHealthCheck(this.containerId); resolve(container); - } catch (ex) { - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); diff --git a/packages/cactus-test-tooling/src/main/typescript/common/containers.ts b/packages/cactus-test-tooling/src/main/typescript/common/containers.ts index 096c5646d6b..380551d4d62 100644 --- a/packages/cactus-test-tooling/src/main/typescript/common/containers.ts +++ b/packages/cactus-test-tooling/src/main/typescript/common/containers.ts @@ -19,6 +19,7 @@ import { Logger, } from "@hyperledger/cactus-common"; import { IDockerPullProgress } from "./i-docker-pull-progress"; +import axios from "axios"; export interface IPruneDockerResourcesRequest { logLevel?: LogLevelDesc; @@ -103,9 +104,21 @@ export class Containers { version, }; return response; - } catch (ex) { - log.error("Failed to get diagnostics of Docker daemon", ex); - throw new RuntimeError("Failed to get diagnostics of Docker daemon", ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + log.error("Failed to get diagnostics of Docker daemon", ex); + throw new RuntimeError( + "Failed to get diagnostics of Docker daemon", + ex as Error, + ); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } /** @@ -522,7 +535,7 @@ export class Containers { try { const { Status } = await Containers.getById(containerId); reachable = Status.endsWith(" (healthy)"); - } catch (ex) { + } catch (ex: unknown) { // FIXME: if the container is slow to start this might trip with a // false positive because there is no container YET in the beginning. // if (ex.stack.includes(`no container by ID"${containerId}"`)) { @@ -530,10 +543,21 @@ export class Containers { // `${fnTag} container crashed while awaiting healthheck -> ${ex.stack}`, // ); // } - if (Date.now() >= startedAt + timeoutMs) { - throw new Error(`${fnTag} timed out (${timeoutMs}ms) -> ${ex.stack}`); + if (axios.isAxiosError(ex)) { + if (Date.now() >= startedAt + timeoutMs) { + throw new Error( + `${fnTag} timed out (${timeoutMs}ms) -> ${ex.stack}`, + ); + } + reachable = false; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); } - reachable = false; } await new Promise((resolve2) => setTimeout(resolve2, 1000)); } while (!reachable); @@ -566,28 +590,70 @@ export class Containers { try { const { all } = await execa("docker", ["system", "df"], { all: true }); log.debug(all); - } catch (ex) { - log.info(`Ignoring failure of docker system df.`, ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + log.info(`Ignoring failure of docker system df.`, ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } try { containers = await docker.pruneContainers(); - } catch (ex) { - log.warn(`Failed to prune docker containers: `, ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + log.warn(`Failed to prune docker containers: `, ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } try { images = await docker.pruneImages(); - } catch (ex) { - log.warn(`Failed to prune docker images: `, ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + log.warn(`Failed to prune docker images: `, ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception:", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } try { volumes = await docker.pruneVolumes(); - } catch (ex) { - log.warn(`Failed to prune docker volumes: `, ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + log.warn(`Failed to prune docker volumes: `, ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError("unexpected exception", JSON.stringify(ex)); + } } try { networks = await docker.pruneNetworks(); - } catch (ex) { - log.warn(`Failed to prune docker networks: `, ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + log.warn(`Failed to prune docker networks: `, ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } const existingImages = await docker.listImages(); @@ -603,10 +669,19 @@ export class Containers { const { all, command } = await execa(binary, args, { all: true }); log.debug(command); log.debug(all); - } catch (ex) { - // The first 3 commands might fail if there are no containers or images - // to delete (e.g. their number is zero) - log.info("Ignoring docker resource cleanup command failure.", ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + // The first 3 commands might fail if there are no containers or images + // to delete (e.g. their number is zero) + log.info("Ignoring docker resource cleanup command failure.", ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } const response: IPruneDockerResourcesResponse = { @@ -620,14 +695,32 @@ export class Containers { try { const { all } = await execa("df", [], { all: true }); log.debug(all); - } catch (ex) { - log.info(`Ignoring failure of df.`, ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + log.info(`Ignoring failure of df.`, ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } try { const { all } = await execa("docker", ["system", "df"], { all: true }); log.debug(all); - } catch (ex) { - log.info(`Ignoring failure of docker system df.`, ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + log.info(`Ignoring failure of docker system df.`, ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } return response; } diff --git a/packages/cactus-test-tooling/src/main/typescript/corda-connector/corda-connector-container.ts b/packages/cactus-test-tooling/src/main/typescript/corda-connector/corda-connector-container.ts index 8d846815616..347130d5ebf 100644 --- a/packages/cactus-test-tooling/src/main/typescript/corda-connector/corda-connector-container.ts +++ b/packages/cactus-test-tooling/src/main/typescript/corda-connector/corda-connector-container.ts @@ -12,6 +12,8 @@ import { } from "@hyperledger/cactus-common"; import { Containers } from "../common/containers"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; /* * Provides default options for Corda connector server @@ -147,9 +149,18 @@ export class CordaConnectorContainer { try { await Containers.waitForHealthCheck(this.containerId); resolve(container); - } catch (ex) { - this.log.error(`Waiting for healthcheck to pass failed:`, ex); - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`Waiting for healthcheck to pass failed:`, ex); + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); diff --git a/packages/cactus-test-tooling/src/main/typescript/corda/corda-test-ledger.ts b/packages/cactus-test-tooling/src/main/typescript/corda/corda-test-ledger.ts index a9a259f106e..6d6e16e85cd 100644 --- a/packages/cactus-test-tooling/src/main/typescript/corda/corda-test-ledger.ts +++ b/packages/cactus-test-tooling/src/main/typescript/corda/corda-test-ledger.ts @@ -21,6 +21,8 @@ import { SAMPLE_CORDAPP_ROOT_DIRS, } from "./sample-cordapp-enum"; import { ICordappJarFile } from "./cordapp-jar-file"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; /* * Contains options for Corda container @@ -197,8 +199,17 @@ export class CordaTestLedger implements ITestLedger { } } while (!isHealthy); resolve(container); - } catch (ex) { - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); @@ -295,9 +306,18 @@ export class CordaTestLedger implements ITestLedger { const ssh = new NodeSSH(); try { await ssh.connect(sshConfig); - } catch (ex) { - this.log.error(`Failed to establish SSH connection to Corda node.`, ex); - throw ex; + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`Failed to establish SSH connection to Corda node.`, ex); + throw ex; + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } const cwd = SAMPLE_CORDAPP_ROOT_DIRS[sampleCordapp]; diff --git a/packages/cactus-test-tooling/src/main/typescript/fabric/fabric-test-ledger-v1.ts b/packages/cactus-test-tooling/src/main/typescript/fabric/fabric-test-ledger-v1.ts index e030da3a1d3..a8c11993ab8 100644 --- a/packages/cactus-test-tooling/src/main/typescript/fabric/fabric-test-ledger-v1.ts +++ b/packages/cactus-test-tooling/src/main/typescript/fabric/fabric-test-ledger-v1.ts @@ -20,6 +20,8 @@ import { LoggerProvider, Bools, } from "@hyperledger/cactus-common"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; /* * Contains options for Fabric container @@ -135,9 +137,18 @@ export class FabricTestLedgerV1 implements ITestLedger { this.log.debug(`createCaClient() caName=%o caUrl=%o`, caName, caUrl); this.log.debug(`createCaClient() tlsOptions=%o`, tlsOptions); return new FabricCAServices(caUrl, tlsOptions, caName); - } catch (ex) { - this.log.error(`createCaClient() Failure:`, ex); - throw new Error(`${fnTag} Inner Exception: ${ex?.message}`); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`createCaClient() Failure:`, ex); + throw new Error(`${fnTag} Inner Exception: ${ex.message}`); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } @@ -196,9 +207,18 @@ export class FabricTestLedgerV1 implements ITestLedger { this.log.debug(`Wallet import of "${enrollmentID}" OK`); return [x509Identity, wallet]; - } catch (ex) { - this.log.error(`enrollUser() Failure:`, ex); - throw new Error(`${fnTag} Exception: ${ex?.message}`); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`enrollUser() Failure:`, ex); + throw new Error(`${fnTag} Exception: ${ex.message}`); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } } @@ -227,9 +247,15 @@ export class FabricTestLedgerV1 implements ITestLedger { await wallet.put("admin", x509Identity); return [x509Identity, wallet]; - } catch (ex) { - this.log.error(`enrollAdmin() Failure:`, ex); - throw new Error(`${fnTag} Exception: ${ex?.message}`); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(`enrollAdmin() Failure:`, ex); + throw new Error(`${fnTag} Exception: ${ex.message}`); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError("unexpected exception with incorrect type"); + } } } @@ -454,8 +480,17 @@ export class FabricTestLedgerV1 implements ITestLedger { try { await this.waitForHealthCheck(); resolve(container); - } catch (ex) { - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); @@ -469,10 +504,21 @@ export class FabricTestLedgerV1 implements ITestLedger { try { const { Status } = await this.getContainerInfo(); reachable = Status.endsWith(" (healthy)"); - } catch (ex) { - reachable = false; - if (Date.now() >= startedAt + timeoutMs) { - throw new Error(`${fnTag} timed out (${timeoutMs}ms) -> ${ex.stack}`); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reachable = false; + if (Date.now() >= startedAt + timeoutMs) { + throw new Error( + `${fnTag} timed out (${timeoutMs}ms) -> ${ex.stack}`, + ); + } + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); } } await new Promise((resolve2) => setTimeout(resolve2, 1000)); diff --git a/packages/cactus-test-tooling/src/main/typescript/go-ipfs/go-ipfs-test-container.ts b/packages/cactus-test-tooling/src/main/typescript/go-ipfs/go-ipfs-test-container.ts index 5c9ce83f6b7..ba9034f8f21 100644 --- a/packages/cactus-test-tooling/src/main/typescript/go-ipfs/go-ipfs-test-container.ts +++ b/packages/cactus-test-tooling/src/main/typescript/go-ipfs/go-ipfs-test-container.ts @@ -7,6 +7,7 @@ import { Logger, Checks, Bools } from "@hyperledger/cactus-common"; import type { LogLevelDesc } from "@hyperledger/cactus-common"; import { LoggerProvider } from "@hyperledger/cactus-common"; import { Containers } from "../common/containers"; +import axios from "axios"; export interface IGoIpfsTestContainerOptions { readonly logLevel?: LogLevelDesc; @@ -150,8 +151,17 @@ export class GoIpfsTestContainer { try { await Containers.waitForHealthCheck(this.containerId.get()); resolve(container); - } catch (ex) { - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); diff --git a/packages/cactus-test-tooling/src/main/typescript/http-echo/http-echo-container.ts b/packages/cactus-test-tooling/src/main/typescript/http-echo/http-echo-container.ts index 84d68f59251..8223de3a3c7 100644 --- a/packages/cactus-test-tooling/src/main/typescript/http-echo/http-echo-container.ts +++ b/packages/cactus-test-tooling/src/main/typescript/http-echo/http-echo-container.ts @@ -3,6 +3,8 @@ import isPortReachable from "is-port-reachable"; import Joi from "joi"; import { EventEmitter } from "events"; import { ITestLedger } from "../i-test-ledger"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; const OPTS_SCHEMA: Joi.Schema = Joi.object().keys({ imageVersion: Joi.string().min(5).required(), @@ -109,8 +111,17 @@ export class HttpEchoContainer implements ITestLedger { await new Promise((resolve2) => setTimeout(resolve2, 100)); } while (!reachable); resolve(container); - } catch (ex) { - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); diff --git a/packages/cactus-test-tooling/src/main/typescript/iroha/iroha-test-ledger.ts b/packages/cactus-test-tooling/src/main/typescript/iroha/iroha-test-ledger.ts index 76510a450a8..6447a341f53 100644 --- a/packages/cactus-test-tooling/src/main/typescript/iroha/iroha-test-ledger.ts +++ b/packages/cactus-test-tooling/src/main/typescript/iroha/iroha-test-ledger.ts @@ -11,6 +11,8 @@ import { import { ITestLedger } from "../i-test-ledger"; import { IKeyPair } from "../i-key-pair"; import { Containers } from "../common/containers"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; /* * Contains options for Iroha container @@ -324,8 +326,17 @@ export class IrohaTestLedger implements ITestLedger { await this.waitForHealthCheck(); this.log.debug(`Healthcheck passing OK.`); resolve(container); - } catch (ex) { - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); diff --git a/packages/cactus-test-tooling/src/main/typescript/keycloak/keycloak-container.ts b/packages/cactus-test-tooling/src/main/typescript/keycloak/keycloak-container.ts index 1cec545ed29..3cad2fd5137 100644 --- a/packages/cactus-test-tooling/src/main/typescript/keycloak/keycloak-container.ts +++ b/packages/cactus-test-tooling/src/main/typescript/keycloak/keycloak-container.ts @@ -14,6 +14,8 @@ import { import { Containers } from "../common/containers"; import RealmRepresentation from "keycloak-admin/lib/defs/realmRepresentation"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; export interface IKeycloakContainerOptions { envVars?: string[]; @@ -132,8 +134,17 @@ export class KeycloakContainer { try { await Containers.waitForHealthCheck(this._containerId); resolve(container); - } catch (ex) { - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); diff --git a/packages/cactus-test-tooling/src/main/typescript/localstack/localstack-container.ts b/packages/cactus-test-tooling/src/main/typescript/localstack/localstack-container.ts index ac8dfc56362..3b60368134d 100644 --- a/packages/cactus-test-tooling/src/main/typescript/localstack/localstack-container.ts +++ b/packages/cactus-test-tooling/src/main/typescript/localstack/localstack-container.ts @@ -10,6 +10,8 @@ import { } from "@hyperledger/cactus-common"; import { Containers } from "../common/containers"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; export interface ILocalStackContainerOptions { imageVersion?: string; @@ -119,8 +121,17 @@ export class LocalStackContainer { try { await Containers.waitForHealthCheck(this._containerId); resolve(container); - } catch (ex) { - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); diff --git a/packages/cactus-test-tooling/src/main/typescript/openethereum/openethereum-test-ledger.ts b/packages/cactus-test-tooling/src/main/typescript/openethereum/openethereum-test-ledger.ts index 6457019ce01..8a181ee5484 100644 --- a/packages/cactus-test-tooling/src/main/typescript/openethereum/openethereum-test-ledger.ts +++ b/packages/cactus-test-tooling/src/main/typescript/openethereum/openethereum-test-ledger.ts @@ -14,6 +14,8 @@ import { } from "@hyperledger/cactus-common"; import { Containers } from "../common/containers"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; export interface IOpenEthereumTestLedgerOptions { envVars?: string[]; @@ -167,8 +169,17 @@ export class OpenEthereumTestLedger { try { await Containers.waitForHealthCheck(this._containerId); resolve(container); - } catch (ex) { - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); diff --git a/packages/cactus-test-tooling/src/main/typescript/postgres/postgres-test-container.ts b/packages/cactus-test-tooling/src/main/typescript/postgres/postgres-test-container.ts index 6de69972dc1..828e8f9eb44 100644 --- a/packages/cactus-test-tooling/src/main/typescript/postgres/postgres-test-container.ts +++ b/packages/cactus-test-tooling/src/main/typescript/postgres/postgres-test-container.ts @@ -11,6 +11,8 @@ import { import { ITestLedger } from "../i-test-ledger"; import { Streams } from "../common/streams"; import { Containers } from "../common/containers"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; /* * Contains options for Postgres container @@ -184,8 +186,17 @@ export class PostgresTestContainer implements ITestLedger { await this.waitForHealthCheck(); this.log.debug(`Healthcheck passing OK.`); resolve(container); - } catch (ex) { - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); diff --git a/packages/cactus-test-tooling/src/main/typescript/quorum/quorum-test-ledger.ts b/packages/cactus-test-tooling/src/main/typescript/quorum/quorum-test-ledger.ts index b2c09f55184..b009c9dec87 100644 --- a/packages/cactus-test-tooling/src/main/typescript/quorum/quorum-test-ledger.ts +++ b/packages/cactus-test-tooling/src/main/typescript/quorum/quorum-test-ledger.ts @@ -17,6 +17,7 @@ import { Streams } from "../common/streams"; import { IKeyPair } from "../i-key-pair"; import { IQuorumGenesisOptions } from "./i-quorum-genesis-options"; import { Containers } from "../common/containers"; +import { RuntimeError } from "run-time-error"; export interface IQuorumTestLedgerConstructorOptions { containerImageVersion?: string; @@ -254,8 +255,17 @@ export class QuorumTestLedger implements ITestLedger { await this.waitForHealthCheck(); this.log.debug("Quorum Test Ledger container passed healthcheck OK"); resolve(container); - } catch (ex) { - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); @@ -270,10 +280,21 @@ export class QuorumTestLedger implements ITestLedger { try { const res = await axios.get(httpUrl); reachable = res.status > 199 && res.status < 300; - } catch (ex) { - reachable = false; - if (Date.now() >= startedAt + timeoutMs) { - throw new Error(`${fnTag} timed out (${timeoutMs}ms) -> ${ex.stack}`); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reachable = false; + if (Date.now() >= startedAt + timeoutMs) { + throw new Error( + `${fnTag} timed out (${timeoutMs}ms) -> ${ex.stack}`, + ); + } + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); } } await new Promise((resolve2) => setTimeout(resolve2, 100)); diff --git a/packages/cactus-test-tooling/src/main/typescript/rustc-container/rustc-container.ts b/packages/cactus-test-tooling/src/main/typescript/rustc-container/rustc-container.ts index 5030ec31c77..ca3ea514214 100644 --- a/packages/cactus-test-tooling/src/main/typescript/rustc-container/rustc-container.ts +++ b/packages/cactus-test-tooling/src/main/typescript/rustc-container/rustc-container.ts @@ -9,6 +9,7 @@ import type { LogLevelDesc } from "@hyperledger/cactus-common"; import { LoggerProvider } from "@hyperledger/cactus-common"; import { Containers } from "../common/containers"; import { RustcBuildCmd } from "./rustc-build-cmd"; +import axios from "axios"; export const K_DEFAULT_RUSTC_CONTAINER_WORKDIR = "/usr/src/host-sources-dir/"; @@ -195,9 +196,18 @@ export class RustcContainer { await Containers.waitForHealthCheck(this.containerId.get()); this.log.debug(`Healthcheck passed OK`); resolve(container); - } catch (ex) { - this.log.error(ex); - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + this.log.error(ex); + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); diff --git a/packages/cactus-test-tooling/src/main/typescript/vault-test-server/vault-test-server.ts b/packages/cactus-test-tooling/src/main/typescript/vault-test-server/vault-test-server.ts index 545bba4c9a4..2c4752d3540 100644 --- a/packages/cactus-test-tooling/src/main/typescript/vault-test-server/vault-test-server.ts +++ b/packages/cactus-test-tooling/src/main/typescript/vault-test-server/vault-test-server.ts @@ -10,6 +10,8 @@ import { } from "@hyperledger/cactus-common"; import { Containers } from "../common/containers"; +import axios from "axios"; +import { RuntimeError } from "run-time-error"; export interface IVaultTestServerOptions { envVars?: string[]; @@ -124,8 +126,17 @@ export class VaultTestServer { try { await Containers.waitForHealthCheck(this._containerId); resolve(container); - } catch (ex) { - reject(ex); + } catch (ex: unknown) { + if (axios.isAxiosError(ex)) { + reject(ex); + } else if (ex instanceof Error) { + throw new RuntimeError("unexpected exception", ex); + } else { + throw new RuntimeError( + "unexpected exception with incorrect type", + JSON.stringify(ex), + ); + } } }); }); diff --git a/packages/cactus-test-tooling/src/test/typescript/integration/common/containers.test.ts b/packages/cactus-test-tooling/src/test/typescript/integration/common/containers.test.ts index f35cd4d7a09..a683b3d0efa 100644 --- a/packages/cactus-test-tooling/src/test/typescript/integration/common/containers.test.ts +++ b/packages/cactus-test-tooling/src/test/typescript/integration/common/containers.test.ts @@ -9,6 +9,7 @@ import { HttpEchoContainer, Containers, } from "../../../../main/typescript/public-api"; +import { RuntimeError } from "run-time-error"; LoggerProvider.setLogLevel("DEBUG"); const log: Logger = LoggerProvider.getOrCreate({ label: "containers-test" }); @@ -114,12 +115,20 @@ test("Can report error if docker daemon is not accessable", async (t: Test) => { }, }); t.fail("Containers.getDiagnostics was supposed to fail but did not."); - } catch (ex) { - t.ok(ex, "exception thrown is truthy OK"); - t.ok(ex.cause, "ex.cause truthy OK"); - t.ok(ex.cause.message, "ex.cause.message truthy OK"); - const causeMsgIsInformative = ex.cause.message.includes(badSocketPath); - t.true(causeMsgIsInformative, "causeMsgIsInformative"); + } catch (ex: unknown) { + if (ex instanceof RuntimeError) { + t.ok(ex, "exception thrown is truthy OK"); + t.ok(ex.cause, "ex.cause truthy OK"); + if (ex.cause instanceof Error) { + t.ok(ex.cause?.message, "ex.cause.message truthy OK"); + const causeMsgIsInformative = ex.cause.message.includes(badSocketPath); + t.true(causeMsgIsInformative, "causeMsgIsInformative"); + } else { + t.fail("cause of exception was not instance of Error", ex); + } + } else { + t.fail("tested code threw an exception that aws not a RuntimeError"); + } } t.end(); }); diff --git a/yarn.lock b/yarn.lock index cc652bc125b..cdbf7956e7f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3533,27 +3533,27 @@ call-me-maybe "^1.0.1" glob-to-regexp "^0.3.0" -"@nestjs/common@7.6.18": - version "7.6.18" - resolved "https://registry.yarnpkg.com/@nestjs/common/-/common-7.6.18.tgz#d89e6d248985eec13af60507a8725cb2142d660a" - integrity sha512-BUJQHNhWzwWOkS4Ryndzd4HTeRObcAWV2Fh+ermyo3q3xYQQzNoEWclJVL/wZec8AONELwIJ+PSpWI53VP0leg== +"@nestjs/common@8.0.7": + version "8.0.7" + resolved "https://registry.yarnpkg.com/@nestjs/common/-/common-8.0.7.tgz#b77d904d22c6d7dd7424b306c5ff4946f183cbcb" + integrity sha512-p9dF6rFE8SYIUphzTCtQ2FoE1NVsAnX5jOPsmRvP0DlleKSfE/SizzkM6YmVUM98yyOvlGuHGV1X0NoSP3azCg== dependencies: - axios "0.21.1" + axios "0.21.4" iterare "1.2.1" - tslib "2.2.0" + tslib "2.3.1" uuid "8.3.2" -"@nestjs/core@7.6.18": - version "7.6.18" - resolved "https://registry.yarnpkg.com/@nestjs/core/-/core-7.6.18.tgz#36448f0ae7f7d08f032e1e7e53b4a4c82ae844d7" - integrity sha512-CGu20OjIxgFDY7RJT5t1TDGL8wSlTSlbZEkn8U5OlICZEB3WIpi98G7ajJpnRWmEgW8S4aDJmRKGjT+Ntj5U4A== +"@nestjs/core@8.0.7": + version "8.0.7" + resolved "https://registry.yarnpkg.com/@nestjs/core/-/core-8.0.7.tgz#49369272a184e62ceb4761f82626a13eeb6cec15" + integrity sha512-A8n+rw8C3yp5hpvmHeQ+x7NjPOe+m/8ITI2tiv8cJeOjPaXn2nhViSB7uwKaNUP1MBgh/7y0HVafFBHzPBZj3g== dependencies: "@nuxtjs/opencollective" "0.3.2" - fast-safe-stringify "2.0.7" + fast-safe-stringify "2.0.8" iterare "1.2.1" - object-hash "2.1.1" + object-hash "2.2.0" path-to-regexp "3.2.0" - tslib "2.2.0" + tslib "2.3.1" uuid "8.3.2" "@ngtools/webpack@12.2.0": @@ -3772,22 +3772,22 @@ dependencies: "@octokit/openapi-types" "^11.2.0" -"@openapitools/openapi-generator-cli@2.3.10": - version "2.3.10" - resolved "https://registry.yarnpkg.com/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.3.10.tgz#c30ff4e85a48682432c793a6450b2d2422bee82c" - integrity sha512-S9cyk6W6vJigiZv7kpoeXF8hWT6kx6iFb14onH64AKJdYfbr8vz9e48YC+C9heFi2dF5ThDGvL3RGTox+V6O1g== +"@openapitools/openapi-generator-cli@2.4.5": + version "2.4.5" + resolved "https://registry.yarnpkg.com/@openapitools/openapi-generator-cli/-/openapi-generator-cli-2.4.5.tgz#74b7b07ec8d307625fb4ec6ddcade10ae3c82849" + integrity sha512-dtZYJMv9XdZEnMwfR5Cq1lykDU4BSLQcxDXwv6fC4XJ4n8mF/bOKJBEKBbxhw1mfC4/PaJjRxwK25EU+b3YDXA== dependencies: - "@nestjs/common" "7.6.18" - "@nestjs/core" "7.6.18" + "@nestjs/common" "8.0.7" + "@nestjs/core" "8.0.7" "@nuxtjs/opencollective" "0.3.2" chalk "4.1.2" - commander "6.2.1" + commander "8.2.0" compare-versions "3.6.0" concurrently "6.2.1" console.table "0.10.0" fs-extra "10.0.0" glob "7.1.6" - inquirer "8.1.2" + inquirer "8.1.5" lodash "4.17.21" reflect-metadata "0.1.13" rxjs "7.3.0" @@ -5841,13 +5841,6 @@ axios-cookiejar-support@^1.0.1: is-redirect "^1.0.0" pify "^5.0.0" -axios@0.21.1: - version "0.21.1" - resolved "https://registry.yarnpkg.com/axios/-/axios-0.21.1.tgz#22563481962f4d6bde9a76d516ef0e5d3c09b2b8" - integrity sha512-dKQiRHxGD9PPRIUNIWvZhPTPpl1rf/OxTYKsqKUDjBwYylTvV7SjSHJb9ratfyzM6wCdLCOYLzs73qpg5c4iGA== - dependencies: - follow-redirects "^1.10.0" - axios@0.21.4, axios@^0.21.0, axios@^0.21.1: version "0.21.4" resolved "https://registry.yarnpkg.com/axios/-/axios-0.21.4.tgz#c67b90dc0568e5c1cf2b0b858c43ba28e2eda575" @@ -7634,16 +7627,21 @@ commander@3.0.2: resolved "https://registry.yarnpkg.com/commander/-/commander-3.0.2.tgz#6837c3fb677ad9933d1cfba42dd14d5117d6b39e" integrity sha512-Gar0ASD4BDyKC4hl4DwHqDrmvjoxWKZigVnAbn5H1owvm4CxCPdb0HQDehwNYMJpla5+M2tPmPARzhtYuwpHow== -commander@6.2.1, commander@^6.2.0: - version "6.2.1" - resolved "https://registry.yarnpkg.com/commander/-/commander-6.2.1.tgz#0792eb682dfbc325999bb2b84fddddba110ac73c" - integrity sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA== +commander@8.2.0: + version "8.2.0" + resolved "https://registry.yarnpkg.com/commander/-/commander-8.2.0.tgz#37fe2bde301d87d47a53adeff8b5915db1381ca8" + integrity sha512-LLKxDvHeL91/8MIyTAD5BFMNtoIwztGPMiM/7Bl8rIPmHCZXRxmSWr91h57dpOpnQ6jIUqEWdXE/uBYMfiVZDA== commander@^2.11.0, commander@^2.12.1, commander@^2.20.0, commander@^2.8.1: version "2.20.3" resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== +commander@^6.2.0: + version "6.2.1" + resolved "https://registry.yarnpkg.com/commander/-/commander-6.2.1.tgz#0792eb682dfbc325999bb2b84fddddba110ac73c" + integrity sha512-U7VdrJFnJgo4xjrHpTzu0yrHPGImdsmD95ZlgYSEajAn2JKzDhDTPG9kBTefmObL2w/ngeZnilk+OV9CG3d7UA== + commander@^7.0.0, commander@^7.2.0: version "7.2.0" resolved "https://registry.yarnpkg.com/commander/-/commander-7.2.0.tgz#a36cb57d0b501ce108e4d20559a150a391d97ab7" @@ -11006,10 +11004,10 @@ fast-levenshtein@^2.0.6, fast-levenshtein@~2.0.6: resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc= -fast-safe-stringify@2.0.7: - version "2.0.7" - resolved "https://registry.yarnpkg.com/fast-safe-stringify/-/fast-safe-stringify-2.0.7.tgz#124aa885899261f68aedb42a7c080de9da608743" - integrity sha512-Utm6CdzT+6xsDk2m8S6uL8VHxNwI6Jub+e9NYTcAms28T84pTa25GJQV9j0CY0N1rM8hK4x6grpF2BQf+2qwVA== +fast-safe-stringify@2.0.8: + version "2.0.8" + resolved "https://registry.yarnpkg.com/fast-safe-stringify/-/fast-safe-stringify-2.0.8.tgz#dc2af48c46cf712b683e849b2bbd446b32de936f" + integrity sha512-lXatBjf3WPjmWD6DpIZxkeSsCOwqI0maYMpgDlx8g4U2qi4lbjA9oH/HD2a87G+KfsUmo5WbJFmqBZlPxtptag== fast-text-encoding@^1.0.0, fast-text-encoding@^1.0.3: version "1.0.3" @@ -11249,7 +11247,7 @@ flatten@^1.0.2: resolved "https://registry.yarnpkg.com/flatten/-/flatten-1.0.3.tgz#c1283ac9f27b368abc1e36d1ff7b04501a30356b" integrity sha512-dVsPA/UwQ8+2uoFe5GHtiBMu48dWLTdsuEd7CKGlZlD78r1TTWBvDuFaFGKCo/ZfEr95Uk56vZoX86OsHkUeIg== -follow-redirects@^1.0.0, follow-redirects@^1.10.0, follow-redirects@^1.12.1, follow-redirects@^1.14.0: +follow-redirects@^1.0.0, follow-redirects@^1.12.1, follow-redirects@^1.14.0: version "1.14.4" resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.14.4.tgz#838fdf48a8bbdd79e52ee51fb1c94e3ed98b9379" integrity sha512-zwGkiSXC1MUJG/qmeIFH2HBJx9u0V46QGUe3YR1fXG8bXQxq7fLj0RjLZQ5nubr9qNJUZrH+xUcwXEoXNpfS+g== @@ -12842,6 +12840,26 @@ inquirer@8.1.2: strip-ansi "^6.0.0" through "^2.3.6" +inquirer@8.1.5: + version "8.1.5" + resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-8.1.5.tgz#2dc5159203c826d654915b5fe6990fd17f54a150" + integrity sha512-G6/9xUqmt/r+UvufSyrPpt84NYwhKZ9jLsgMbQzlx804XErNupor8WQdBnBRrXmBfTPpuwf1sV+ss2ovjgdXIg== + dependencies: + ansi-escapes "^4.2.1" + chalk "^4.1.1" + cli-cursor "^3.1.0" + cli-width "^3.0.0" + external-editor "^3.0.3" + figures "^3.0.0" + lodash "^4.17.21" + mute-stream "0.0.8" + ora "^5.4.1" + run-async "^2.4.0" + rxjs "^7.2.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + through "^2.3.6" + inquirer@^7.3.3: version "7.3.3" resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-7.3.3.tgz#04d176b2af04afc157a83fd7c100e98ee0aad003" @@ -17414,12 +17432,7 @@ object-copy@^0.1.0: define-property "^0.2.5" kind-of "^3.0.3" -object-hash@2.1.1: - version "2.1.1" - resolved "https://registry.yarnpkg.com/object-hash/-/object-hash-2.1.1.tgz#9447d0279b4fcf80cff3259bf66a1dc73afabe09" - integrity sha512-VOJmgmS+7wvXf8CjbQmimtCnEx3IAoLxI3fp2fbWehxrWBcAQFbk+vcwb6vzR0VZv/eNCJ/27j151ZTwqW/JeQ== - -object-hash@^2.1.1: +object-hash@2.2.0, object-hash@^2.1.1: version "2.2.0" resolved "https://registry.yarnpkg.com/object-hash/-/object-hash-2.2.0.tgz#5ad518581eefc443bd763472b8ff2e9c2c0d54a5" integrity sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw== @@ -17626,7 +17639,7 @@ optjs@~3.2.2: resolved "https://registry.yarnpkg.com/optjs/-/optjs-3.2.2.tgz#69a6ce89c442a44403141ad2f9b370bd5bb6f4ee" integrity sha1-aabOicRCpEQDFBrS+bNwvVu29O4= -ora@5.4.1, ora@^5.3.0: +ora@5.4.1, ora@^5.3.0, ora@^5.4.1: version "5.4.1" resolved "https://registry.yarnpkg.com/ora/-/ora-5.4.1.tgz#1b2678426af4ac4a509008e5e4ac9e9959db9e18" integrity sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ== @@ -22409,26 +22422,21 @@ tslib@1.13.0: resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.13.0.tgz#c881e13cc7015894ed914862d276436fa9a47043" integrity sha512-i/6DQjL8Xf3be4K/E6Wgpekn5Qasl1usyw++dAA35Ue5orEn65VIxOA+YvNNl9HV3qv70T7CNwjODHZrLwvd1Q== -tslib@2.2.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.2.0.tgz#fb2c475977e35e241311ede2693cee1ec6698f5c" - integrity sha512-gS9GVHRU+RGn5KQM2rllAlR3dU6m7AcpJKdtH8gFvQiC4Otgk98XnmMU+nZenHt/+VhnBPWwgrJsyrdcw6i23w== - tslib@2.3.0: version "2.3.0" resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.0.tgz#803b8cdab3e12ba581a4ca41c8839bbb0dacb09e" integrity sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg== +tslib@2.3.1, tslib@^2, tslib@^2.0.0, tslib@^2.0.3, tslib@^2.1.0, tslib@^2.2.0: + version "2.3.1" + resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" + integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== + tslib@^1.10.0, tslib@^1.13.0, tslib@^1.8.1, tslib@^1.9.0, tslib@^1.9.3: version "1.14.1" resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00" integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg== -tslib@^2, tslib@^2.0.0, tslib@^2.0.3, tslib@^2.1.0, tslib@^2.2.0: - version "2.3.1" - resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.3.1.tgz#e8a335add5ceae51aa261d32a490158ef042ef01" - integrity sha512-77EbyPPpMz+FRFRuAFlWMtmgUWGe9UOG2Z25NqCwiIjRhOf5iKGuzSe5P2w1laq+FkRy4p+PCuVkJSGkzTEKVw== - tslib@~2.1.0: version "2.1.0" resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.1.0.tgz#da60860f1c2ecaa5703ab7d39bc05b6bf988b97a" @@ -22632,6 +22640,11 @@ typescript@4.3.5: resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.3.5.tgz#4d1c37cc16e893973c45a06886b7113234f119f4" integrity sha512-DqQgihaQ9cUrskJo9kIyW/+g0Vxsk8cDtZ52a3NGh0YNTfpUSArXSohyUGnvbPazEPLu398C0UxmKSOrPumUzA== +typescript@4.4.3, typescript@^4.4.3: + version "4.4.3" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.4.3.tgz#bdc5407caa2b109efd4f82fe130656f977a29324" + integrity sha512-4xfscpisVgqqDfPaJo5vkd+Qd/ItkoagnHpufr+i2QCHBsNYp+G7UAoyFl8aPtx879u38wPV65rZ8qbGZijalA== + typescript@^3.9.10: version "3.9.10" resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.9.10.tgz#70f3910ac7a51ed6bef79da7800690b19bf778b8"