From d7fa853a8fc0dd3a6f635a00d6862bfdef97f424 Mon Sep 17 00:00:00 2001 From: tabcat Date: Mon, 20 Mar 2023 09:41:52 -0500 Subject: [PATCH] fix: replace err-code with CodeError (#1532) Replaces [err-code](https://github.com/IndigoUnited/js-err-code/blob/master/index.js) with [CodeError](https://github.com/libp2p/js-libp2p-interfaces/pull/314) Related: #1269 Changes - removes err-code from dependencies - adds @libp2p/interfaces@3.2.0 to dependencies - uses CodeError in place of err-code --------- Co-authored-by: achingbrain --- package.json | 3 +- src/circuit/transport/index.ts | 8 ++-- src/components.ts | 26 ++++++------- src/config.ts | 8 ++-- src/connection-manager/dialer/dial-request.ts | 10 ++--- src/connection-manager/dialer/index.ts | 12 +++--- src/connection-manager/index.ts | 8 ++-- src/connection/index.ts | 6 +-- src/content-routing/index.ts | 16 ++++---- src/content-routing/utils.ts | 4 +- src/dht/dht-content-routing.ts | 4 +- src/dht/dht-peer-routing.ts | 4 +- src/dht/dummy-dht.ts | 24 ++++++------ src/fetch/index.ts | 12 +++--- src/get-peer.ts | 6 +-- src/identify/index.ts | 14 +++---- src/libp2p.ts | 10 ++--- src/nat-manager.ts | 4 +- src/peer-routing.ts | 10 ++--- src/ping/index.ts | 4 +- src/pnet/index.ts | 6 +-- src/pubsub/dummy-pubsub.ts | 18 ++++----- src/registrar.ts | 8 ++-- src/transport-manager.ts | 12 +++--- src/upgrader.ts | 38 +++++++++---------- 25 files changed, 137 insertions(+), 138 deletions(-) diff --git a/package.json b/package.json index d3b1c8fe9f..19db9b7268 100644 --- a/package.json +++ b/package.json @@ -121,7 +121,7 @@ "@libp2p/interface-registrar": "^2.0.3", "@libp2p/interface-stream-muxer": "^3.0.0", "@libp2p/interface-transport": "^2.1.0", - "@libp2p/interfaces": "^3.0.3", + "@libp2p/interfaces": "^3.2.0", "@libp2p/keychain": "^2.0.0", "@libp2p/logger": "^2.0.1", "@libp2p/multistream-select": "^3.0.0", @@ -138,7 +138,6 @@ "abortable-iterator": "^4.0.2", "any-signal": "^3.0.0", "datastore-core": "^9.0.0", - "err-code": "^3.0.1", "interface-datastore": "^8.0.0", "it-all": "^2.0.0", "it-drain": "^2.0.0", diff --git a/src/circuit/transport/index.ts b/src/circuit/transport/index.ts index a76e320fc8..d95233ee36 100644 --- a/src/circuit/transport/index.ts +++ b/src/circuit/transport/index.ts @@ -1,6 +1,5 @@ import { StopMessage, HopMessage, Status } from '../pb/index.js' import { logger } from '@libp2p/logger' -import createError from 'err-code' import * as mafmt from '@multiformats/mafmt' import { multiaddr } from '@multiformats/multiaddr' import { codes } from '../../errors.js' @@ -23,6 +22,7 @@ import type { ContentRouting } from '@libp2p/interface-content-routing' import { CIRCUIT_PROTO_CODE, RELAY_V2_HOP_CODEC, RELAY_V2_STOP_CODEC } from '../constants.js' import { RelayStoreInit, ReservationStore } from './reservation-store.js' import { RelayDiscovery, RelayDiscoveryComponents } from './discovery.js' +import { CodeError } from '@libp2p/interfaces/errors' const log = logger('libp2p:circuit-relay:transport') @@ -154,7 +154,7 @@ class CircuitRelayTransport implements Transport { if (ma.protoCodes().filter(code => code === CIRCUIT_PROTO_CODE).length !== 1) { const errMsg = 'Invalid circuit relay address' log.error(errMsg, ma) - throw createError(new Error(errMsg), codes.ERR_RELAYED_DIAL) + throw new CodeError(errMsg, codes.ERR_RELAYED_DIAL) } // Check the multiaddr to see if it contains a relay and a destination peer @@ -167,7 +167,7 @@ class CircuitRelayTransport implements Transport { if (relayId == null || destinationId == null) { const errMsg = 'Circuit relay dial failed as addresses did not have peer id' log.error(errMsg) - throw createError(new Error(errMsg), codes.ERR_RELAYED_DIAL) + throw new CodeError(errMsg, codes.ERR_RELAYED_DIAL) } const relayPeer = peerIdFromString(relayId) @@ -223,7 +223,7 @@ class CircuitRelayTransport implements Transport { const status = await hopstr.read() if (status.status !== Status.OK) { - throw createError(new Error(`failed to connect via relay with status ${status?.status?.toString() ?? 'undefined'}`), codes.ERR_HOP_REQUEST_FAILED) + throw new CodeError(`failed to connect via relay with status ${status?.status?.toString() ?? 'undefined'}`, codes.ERR_HOP_REQUEST_FAILED) } // TODO: do something with limit and transient connection diff --git a/src/components.ts b/src/components.ts index ee60acbc92..805141aa92 100644 --- a/src/components.ts +++ b/src/components.ts @@ -1,4 +1,4 @@ -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import type { ConnectionProtector } from '@libp2p/interface-connection' import type { ContentRouting } from '@libp2p/interface-content-routing' import type { AddressManager } from '@libp2p/interface-address-manager' @@ -157,7 +157,7 @@ export class DefaultComponents implements Components, Startable { get peerId (): PeerId { if (this._peerId == null) { - throw errCode(new Error('peerId not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('peerId not set', 'ERR_SERVICE_MISSING') } return this._peerId @@ -169,7 +169,7 @@ export class DefaultComponents implements Components, Startable { get addressManager (): AddressManager { if (this._addressManager == null) { - throw errCode(new Error('addressManager not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('addressManager not set', 'ERR_SERVICE_MISSING') } return this._addressManager @@ -181,7 +181,7 @@ export class DefaultComponents implements Components, Startable { get peerStore (): PeerStore { if (this._peerStore == null) { - throw errCode(new Error('peerStore not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('peerStore not set', 'ERR_SERVICE_MISSING') } return this._peerStore @@ -193,7 +193,7 @@ export class DefaultComponents implements Components, Startable { get upgrader (): Upgrader { if (this._upgrader == null) { - throw errCode(new Error('upgrader not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('upgrader not set', 'ERR_SERVICE_MISSING') } return this._upgrader @@ -205,7 +205,7 @@ export class DefaultComponents implements Components, Startable { get registrar (): Registrar { if (this._registrar == null) { - throw errCode(new Error('registrar not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('registrar not set', 'ERR_SERVICE_MISSING') } return this._registrar @@ -217,7 +217,7 @@ export class DefaultComponents implements Components, Startable { get connectionManager (): ConnectionManager { if (this._connectionManager == null) { - throw errCode(new Error('connectionManager not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('connectionManager not set', 'ERR_SERVICE_MISSING') } return this._connectionManager @@ -229,7 +229,7 @@ export class DefaultComponents implements Components, Startable { get transportManager (): TransportManager { if (this._transportManager == null) { - throw errCode(new Error('transportManager not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('transportManager not set', 'ERR_SERVICE_MISSING') } return this._transportManager @@ -241,7 +241,7 @@ export class DefaultComponents implements Components, Startable { get connectionGater (): ConnectionGater { if (this._connectionGater == null) { - throw errCode(new Error('connectionGater not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('connectionGater not set', 'ERR_SERVICE_MISSING') } return this._connectionGater @@ -253,7 +253,7 @@ export class DefaultComponents implements Components, Startable { get contentRouting (): ContentRouting { if (this._contentRouting == null) { - throw errCode(new Error('contentRouting not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('contentRouting not set', 'ERR_SERVICE_MISSING') } return this._contentRouting @@ -265,7 +265,7 @@ export class DefaultComponents implements Components, Startable { get peerRouting (): PeerRouting { if (this._peerRouting == null) { - throw errCode(new Error('peerRouting not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('peerRouting not set', 'ERR_SERVICE_MISSING') } return this._peerRouting @@ -277,7 +277,7 @@ export class DefaultComponents implements Components, Startable { get datastore (): Datastore { if (this._datastore == null) { - throw errCode(new Error('datastore not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('datastore not set', 'ERR_SERVICE_MISSING') } return this._datastore @@ -297,7 +297,7 @@ export class DefaultComponents implements Components, Startable { get dialer (): Dialer { if (this._dialer == null) { - throw errCode(new Error('dialer not set'), 'ERR_SERVICE_MISSING') + throw new CodeError('dialer not set', 'ERR_SERVICE_MISSING') } return this._dialer diff --git a/src/config.ts b/src/config.ts index 651d418294..4f9a3e7b7e 100644 --- a/src/config.ts +++ b/src/config.ts @@ -7,7 +7,7 @@ import { FaultTolerance } from '@libp2p/interface-transport' import type { Multiaddr } from '@multiformats/multiaddr' import type { Libp2pInit } from './index.js' import { codes, messages } from './errors.js' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import type { RecursivePartial } from '@libp2p/interfaces' import { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe' @@ -92,15 +92,15 @@ export function validateConfig (opts: RecursivePartial): Libp2pInit const resultingOptions: Libp2pInit = mergeOptions(DefaultConfig, opts) if (resultingOptions.transports == null || resultingOptions.transports.length < 1) { - throw errCode(new Error(messages.ERR_TRANSPORTS_REQUIRED), codes.ERR_TRANSPORTS_REQUIRED) + throw new CodeError(messages.ERR_TRANSPORTS_REQUIRED, codes.ERR_TRANSPORTS_REQUIRED) } if (resultingOptions.connectionEncryption == null || resultingOptions.connectionEncryption.length === 0) { - throw errCode(new Error(messages.CONN_ENCRYPTION_REQUIRED), codes.CONN_ENCRYPTION_REQUIRED) + throw new CodeError(messages.CONN_ENCRYPTION_REQUIRED, codes.CONN_ENCRYPTION_REQUIRED) } if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef - throw errCode(new Error(messages.ERR_PROTECTOR_REQUIRED), codes.ERR_PROTECTOR_REQUIRED) + throw new CodeError(messages.ERR_PROTECTOR_REQUIRED, codes.ERR_PROTECTOR_REQUIRED) } // Append user agent version to default AGENT_VERSION depending on the environment diff --git a/src/connection-manager/dialer/dial-request.ts b/src/connection-manager/dialer/dial-request.ts index d0034518b3..ad2305abfa 100644 --- a/src/connection-manager/dialer/dial-request.ts +++ b/src/connection-manager/dialer/dial-request.ts @@ -1,4 +1,4 @@ -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { anySignal } from 'any-signal' import FIFO from 'p-fifo' import { setMaxListeners } from 'events' @@ -50,7 +50,7 @@ export class DialRequest { // If no tokens are available, throw if (tokens.length < 1) { - throw errCode(new Error('No dial tokens available'), codes.ERR_NO_DIAL_TOKENS) + throw new CodeError('No dial tokens available', codes.ERR_NO_DIAL_TOKENS) } const tokenHolder = new FIFO() @@ -87,12 +87,12 @@ export class DialRequest { // End attempt once another attempt succeeded if (done) { this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0]) - throw errCode(new Error('dialAction already succeeded'), codes.ERR_ALREADY_SUCCEEDED) + throw new CodeError('dialAction already succeeded', codes.ERR_ALREADY_SUCCEEDED) } const controller = dialAbortControllers[i] if (controller == null) { - throw errCode(new Error('dialAction did not come with an AbortController'), codes.ERR_INVALID_PARAMETERS) + throw new CodeError('dialAction did not come with an AbortController', codes.ERR_INVALID_PARAMETERS) } let conn try { @@ -116,7 +116,7 @@ export class DialRequest { // Notify Promise.any that attempt was not successful // to prevent from returning undefined despite there // were successful dial attempts - throw errCode(new Error('dialAction led to empty object'), codes.ERR_TRANSPORT_DIAL_FAILED) + throw new CodeError('dialAction led to empty object', codes.ERR_TRANSPORT_DIAL_FAILED) } else { // This dial succeeded, don't attempt anything else done = true diff --git a/src/connection-manager/dialer/index.ts b/src/connection-manager/dialer/index.ts index a7ec43ca62..7ddb3f390f 100644 --- a/src/connection-manager/dialer/index.ts +++ b/src/connection-manager/dialer/index.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { isMultiaddr, Multiaddr, Resolver, multiaddr, resolvers } from '@multiformats/multiaddr' import { TimeoutController } from 'timeout-abort-controller' import { anySignal } from 'any-signal' @@ -156,7 +156,7 @@ export class DefaultDialer implements Startable, Dialer { if (peerId != null) { if (this.components.peerId.equals(peerId)) { - throw errCode(new Error('Tried to dial self'), codes.ERR_DIALED_SELF) + throw new CodeError('Tried to dial self', codes.ERR_DIALED_SELF) } if (multiaddr != null) { @@ -165,7 +165,7 @@ export class DefaultDialer implements Startable, Dialer { } if ((await this.components.connectionGater.denyDialPeer?.(peerId)) === true) { - throw errCode(new Error('The dial request is blocked by gater.allowDialPeer'), codes.ERR_PEER_DIAL_INTERCEPTED) + throw new CodeError('The dial request is blocked by gater.allowDialPeer', codes.ERR_PEER_DIAL_INTERCEPTED) } } @@ -195,7 +195,7 @@ export class DefaultDialer implements Startable, Dialer { } if (dialTarget.addrs.length === 0) { - throw errCode(new Error('The dial request has no valid addresses'), codes.ERR_NO_VALID_ADDRESSES) + throw new CodeError('The dial request has no valid addresses', codes.ERR_NO_VALID_ADDRESSES) } // try to join an in-flight dial for this peer if one is available @@ -267,7 +267,7 @@ export class DefaultDialer implements Startable, Dialer { addrs = [...new Set(addrs.map(ma => ma.toString()))].map(ma => multiaddr(ma)) if (addrs.length > this.maxAddrsToDial) { - throw errCode(new Error('dial with more addresses than allowed'), codes.ERR_TOO_MANY_ADDRESSES) + throw new CodeError('dial with more addresses than allowed', codes.ERR_TOO_MANY_ADDRESSES) } const peerId = isPeerId(peerIdOrMultiaddr.peerId) ? peerIdOrMultiaddr.peerId : undefined @@ -324,7 +324,7 @@ export class DefaultDialer implements Startable, Dialer { */ const dialAction: DialAction = async (addr, options = {}) => { if (options.signal?.aborted === true) { - throw errCode(new Error('already aborted'), codes.ERR_ALREADY_ABORTED) + throw new CodeError('already aborted', codes.ERR_ALREADY_ABORTED) } return await this.components.transportManager.dial(addr, options).catch(err => { diff --git a/src/connection-manager/index.ts b/src/connection-manager/index.ts index 01712a6f83..9dca352369 100644 --- a/src/connection-manager/index.ts +++ b/src/connection-manager/index.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import mergeOptions from 'merge-options' import { LatencyMonitor, SummaryObject } from './latency-monitor.js' import type { AbortOptions } from '@libp2p/interfaces' @@ -163,7 +163,7 @@ export class DefaultConnectionManager extends EventEmitter { if (this.stat.status === CLOSING) { - throw errCode(new Error('the connection is being closed'), 'ERR_CONNECTION_BEING_CLOSED') + throw new CodeError('the connection is being closed', 'ERR_CONNECTION_BEING_CLOSED') } if (this.stat.status === CLOSED) { - throw errCode(new Error('the connection is closed'), 'ERR_CONNECTION_CLOSED') + throw new CodeError('the connection is closed', 'ERR_CONNECTION_CLOSED') } if (!Array.isArray(protocols)) { diff --git a/src/content-routing/index.ts b/src/content-routing/index.ts index f1cedcef73..a3cfe7fc9c 100644 --- a/src/content-routing/index.ts +++ b/src/content-routing/index.ts @@ -1,4 +1,4 @@ -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { messages, codes } from '../errors.js' import { storeAddresses, @@ -54,7 +54,7 @@ export class CompoundContentRouting implements ContentRouting, Startable { */ async * findProviders (key: CID, options: AbortOptions = {}): AsyncIterable { if (this.routers.length === 0) { - throw errCode(new Error('No content this.routers available'), codes.ERR_NO_ROUTERS_AVAILABLE) + throw new CodeError('No content this.routers available', codes.ERR_NO_ROUTERS_AVAILABLE) } yield * pipe( @@ -73,7 +73,7 @@ export class CompoundContentRouting implements ContentRouting, Startable { */ async provide (key: CID, options: AbortOptions = {}): Promise { if (this.routers.length === 0) { - throw errCode(new Error('No content routers available'), codes.ERR_NO_ROUTERS_AVAILABLE) + throw new CodeError('No content routers available', codes.ERR_NO_ROUTERS_AVAILABLE) } await Promise.all(this.routers.map(async (router) => { await router.provide(key, options) })) @@ -84,7 +84,7 @@ export class CompoundContentRouting implements ContentRouting, Startable { */ async put (key: Uint8Array, value: Uint8Array, options?: AbortOptions): Promise { if (!this.isStarted()) { - throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED) + throw new CodeError(messages.NOT_STARTED_YET, codes.DHT_NOT_STARTED) } const dht = this.components.dht @@ -100,7 +100,7 @@ export class CompoundContentRouting implements ContentRouting, Startable { */ async get (key: Uint8Array, options?: AbortOptions): Promise { if (!this.isStarted()) { - throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED) + throw new CodeError(messages.NOT_STARTED_YET, codes.DHT_NOT_STARTED) } const dht = this.components.dht @@ -113,7 +113,7 @@ export class CompoundContentRouting implements ContentRouting, Startable { } } - throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND) + throw new CodeError(messages.NOT_FOUND, codes.ERR_NOT_FOUND) } /** @@ -121,7 +121,7 @@ export class CompoundContentRouting implements ContentRouting, Startable { */ async * getMany (key: Uint8Array, nVals: number, options: AbortOptions): AsyncIterable<{ from: PeerId, val: Uint8Array }> { if (!this.isStarted()) { - throw errCode(new Error(messages.NOT_STARTED_YET), codes.DHT_NOT_STARTED) + throw new CodeError(messages.NOT_STARTED_YET, codes.DHT_NOT_STARTED) } if (nVals == null || nVals === 0) { @@ -146,7 +146,7 @@ export class CompoundContentRouting implements ContentRouting, Startable { } if (gotValues === 0) { - throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND) + throw new CodeError(messages.NOT_FOUND, codes.ERR_NOT_FOUND) } } } diff --git a/src/content-routing/utils.ts b/src/content-routing/utils.ts index 70832688e8..18dc0af347 100644 --- a/src/content-routing/utils.ts +++ b/src/content-routing/utils.ts @@ -1,4 +1,4 @@ -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import filter from 'it-filter' import map from 'it-map' import type { Source } from 'it-stream-types' @@ -49,6 +49,6 @@ export async function * requirePeers (source: Source, min: number = 1) } if (seen < min) { - throw errCode(new Error('not found'), 'NOT_FOUND') + throw new CodeError('not found', 'NOT_FOUND') } } diff --git a/src/dht/dht-content-routing.ts b/src/dht/dht-content-routing.ts index de9f77726c..4c10d5bcf0 100644 --- a/src/dht/dht-content-routing.ts +++ b/src/dht/dht-content-routing.ts @@ -1,5 +1,5 @@ import drain from 'it-drain' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import type { DHT } from '@libp2p/interface-dht' import type { ContentRouting } from '@libp2p/interface-content-routing' import type { CID } from 'multiformats/cid' @@ -39,6 +39,6 @@ export class DHTContentRouting implements ContentRouting { } } - throw errCode(new Error('Not found'), 'ERR_NOT_FOUND') + throw new CodeError('Not found', 'ERR_NOT_FOUND') } } diff --git a/src/dht/dht-peer-routing.ts b/src/dht/dht-peer-routing.ts index fe7e3580f8..61ff4f4820 100644 --- a/src/dht/dht-peer-routing.ts +++ b/src/dht/dht-peer-routing.ts @@ -1,4 +1,4 @@ -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { messages, codes } from '../errors.js' import type { PeerRouting } from '@libp2p/interface-peer-routing' import type { DHT } from '@libp2p/interface-dht' @@ -23,7 +23,7 @@ export class DHTPeerRouting implements PeerRouting { } } - throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND) + throw new CodeError(messages.NOT_FOUND, codes.ERR_NOT_FOUND) } async * getClosestPeers (key: Uint8Array, options: AbortOptions = {}): AsyncIterable { diff --git a/src/dht/dummy-dht.ts b/src/dht/dummy-dht.ts index e2f06526fe..19e56f65df 100644 --- a/src/dht/dummy-dht.ts +++ b/src/dht/dummy-dht.ts @@ -1,6 +1,6 @@ import type { DualDHT, QueryEvent, SingleDHT } from '@libp2p/interface-dht' import type { PeerDiscoveryEvents } from '@libp2p/interface-peer-discovery' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { messages, codes } from '../errors.js' import { EventEmitter } from '@libp2p/interfaces/events' import { symbol } from '@libp2p/interface-peer-discovery' @@ -15,46 +15,46 @@ export class DummyDHT extends EventEmitter implements DualD } get wan (): SingleDHT { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } get lan (): SingleDHT { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } get (): AsyncIterable { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } findProviders (): AsyncIterable { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } findPeer (): AsyncIterable { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } getClosestPeers (): AsyncIterable { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } provide (): AsyncIterable { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } put (): AsyncIterable { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } async getMode (): Promise<'client' | 'server'> { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } async setMode (): Promise { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } async refreshRoutingTable (): Promise { - throw errCode(new Error(messages.DHT_DISABLED), codes.DHT_DISABLED) + throw new CodeError(messages.DHT_DISABLED, codes.DHT_DISABLED) } } diff --git a/src/fetch/index.ts b/src/fetch/index.ts index 7ab75508ba..75dba5bb64 100644 --- a/src/fetch/index.ts +++ b/src/fetch/index.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { codes } from '../errors.js' import * as lp from 'it-length-prefixed' import { FetchRequest, FetchResponse } from './pb/proto.js' @@ -134,7 +134,7 @@ export class FetchService implements Startable { const buf = await first(source) if (buf == null) { - throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE) + throw new CodeError('No data received', codes.ERR_INVALID_MESSAGE) } const response = FetchResponse.decode(buf) @@ -151,11 +151,11 @@ export class FetchService implements Startable { case (FetchResponse.StatusCode.ERROR): { log('received status for %s error', key) const errmsg = uint8arrayToString(response.data) - throw errCode(new Error('Error in fetch protocol response: ' + errmsg), codes.ERR_INVALID_PARAMETERS) + throw new CodeError('Error in fetch protocol response: ' + errmsg, codes.ERR_INVALID_PARAMETERS) } default: { log('received status for %s unknown', key) - throw errCode(new Error('Unknown response status'), codes.ERR_INVALID_MESSAGE) + throw new CodeError('Unknown response status', codes.ERR_INVALID_MESSAGE) } } } @@ -189,7 +189,7 @@ export class FetchService implements Startable { const buf = await first(source) if (buf == null) { - throw errCode(new Error('No data received'), codes.ERR_INVALID_MESSAGE) + throw new CodeError('No data received', codes.ERR_INVALID_MESSAGE) } // for await (const buf of source) { @@ -245,7 +245,7 @@ export class FetchService implements Startable { */ registerLookupFunction (prefix: string, lookup: LookupFunction): void { if (this.lookupFunctions.has(prefix)) { - throw errCode(new Error("Fetch protocol handler for key prefix '" + prefix + "' already registered"), codes.ERR_KEY_ALREADY_EXISTS) + throw new CodeError(`Fetch protocol handler for key prefix '${prefix}' already registered`, codes.ERR_KEY_ALREADY_EXISTS) } this.lookupFunctions.set(prefix, lookup) diff --git a/src/get-peer.ts b/src/get-peer.ts index 316ca2c057..ed8e544876 100644 --- a/src/get-peer.ts +++ b/src/get-peer.ts @@ -1,7 +1,7 @@ import { peerIdFromString } from '@libp2p/peer-id' import type { Multiaddr } from '@multiformats/multiaddr' import { isMultiaddr } from '@multiformats/multiaddr' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { codes } from './errors.js' import { isPeerId } from '@libp2p/interface-peer-id' import type { PeerId } from '@libp2p/interface-peer-id' @@ -25,8 +25,8 @@ export function getPeerAddress (peer: PeerId | Multiaddr): { peerId?: PeerId, mu } } - throw errCode( - new Error(`${peer} is not a PeerId or a Multiaddr`), // eslint-disable-line @typescript-eslint/restrict-template-expressions + throw new CodeError( + `${peer} is not a PeerId or a Multiaddr`, // eslint-disable-line @typescript-eslint/restrict-template-expressions codes.ERR_INVALID_MULTIADDR ) } diff --git a/src/identify/index.ts b/src/identify/index.ts index 591bf5795d..23d829b346 100644 --- a/src/identify/index.ts +++ b/src/identify/index.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import * as lp from 'it-length-prefixed' import { pipe } from 'it-pipe' import first from 'it-first' @@ -273,13 +273,13 @@ export class IdentifyService implements Startable { ) if (data == null) { - throw errCode(new Error('No data could be retrieved'), codes.ERR_CONNECTION_ENDED) + throw new CodeError('No data could be retrieved', codes.ERR_CONNECTION_ENDED) } try { return Identify.decode(data) } catch (err: any) { - throw errCode(err, codes.ERR_INVALID_MESSAGE) + throw new CodeError(String(err), codes.ERR_INVALID_MESSAGE) } } finally { if (timeoutController != null) { @@ -311,17 +311,17 @@ export class IdentifyService implements Startable { } = message if (publicKey == null) { - throw errCode(new Error('public key was missing from identify message'), codes.ERR_MISSING_PUBLIC_KEY) + throw new CodeError('public key was missing from identify message', codes.ERR_MISSING_PUBLIC_KEY) } const id = await peerIdFromKeys(publicKey) if (!connection.remotePeer.equals(id)) { - throw errCode(new Error('identified peer does not match the expected peer'), codes.ERR_INVALID_PEER) + throw new CodeError('identified peer does not match the expected peer', codes.ERR_INVALID_PEER) } if (this.components.peerId.equals(id)) { - throw errCode(new Error('identified peer is our own peer id?'), codes.ERR_INVALID_PEER) + throw new CodeError('identified peer is our own peer id?', codes.ERR_INVALID_PEER) } // Get the observedAddr if there is one @@ -334,7 +334,7 @@ export class IdentifyService implements Startable { const envelope = await RecordEnvelope.openAndCertify(signedPeerRecord, PeerRecord.DOMAIN) if (!envelope.peerId.equals(id)) { - throw errCode(new Error('identified peer does not match the expected peer'), codes.ERR_INVALID_PEER) + throw new CodeError('identified peer does not match the expected peer', codes.ERR_INVALID_PEER) } if (await this.components.peerStore.addressBook.consumePeerRecord(envelope)) { diff --git a/src/libp2p.ts b/src/libp2p.ts index 957a6c1324..b629cff5be 100644 --- a/src/libp2p.ts +++ b/src/libp2p.ts @@ -40,7 +40,7 @@ import type { PeerStore } from '@libp2p/interface-peer-store' import type { DualDHT } from '@libp2p/interface-dht' import { concat as uint8ArrayConcat } from 'uint8arrays/concat' import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { unmarshalPublicKey } from '@libp2p/crypto/keys' import type { Metrics } from '@libp2p/interface-metrics' import { DummyDHT } from './dht/dummy-dht.js' @@ -370,13 +370,13 @@ export class Libp2pNode extends EventEmitter implements Libp2p { async dialProtocol (peer: PeerId | Multiaddr, protocols: string | string[], options: AbortOptions = {}): Promise { if (protocols == null) { - throw errCode(new Error('no protocols were provided to open a stream'), codes.ERR_INVALID_PROTOCOLS_FOR_STREAM) + throw new CodeError('no protocols were provided to open a stream', codes.ERR_INVALID_PROTOCOLS_FOR_STREAM) } protocols = Array.isArray(protocols) ? protocols : [protocols] if (protocols.length === 0) { - throw errCode(new Error('no protocols were provided to open a stream'), codes.ERR_INVALID_PROTOCOLS_FOR_STREAM) + throw new CodeError('no protocols were provided to open a stream', codes.ERR_INVALID_PROTOCOLS_FOR_STREAM) } const connection = await this.dial(peer, options) @@ -417,7 +417,7 @@ export class Libp2pNode extends EventEmitter implements Libp2p { } if (this.dht == null) { - throw errCode(new Error('Public key was not in the peer store and the DHT is not enabled'), codes.ERR_NO_ROUTERS_AVAILABLE) + throw new CodeError('Public key was not in the peer store and the DHT is not enabled', codes.ERR_NO_ROUTERS_AVAILABLE) } const peerKey = uint8ArrayConcat([ @@ -436,7 +436,7 @@ export class Libp2pNode extends EventEmitter implements Libp2p { } } - throw errCode(new Error(`Node not responding with its public key: ${peer.toString()}`), codes.ERR_INVALID_RECORD) + throw new CodeError(`Node not responding with its public key: ${peer.toString()}`, codes.ERR_INVALID_RECORD) } async fetch (peer: PeerId | Multiaddr, key: string, options: AbortOptions = {}): Promise { diff --git a/src/nat-manager.ts b/src/nat-manager.ts index 13c859973c..65af5bb5e7 100644 --- a/src/nat-manager.ts +++ b/src/nat-manager.ts @@ -4,7 +4,7 @@ import { fromNodeAddress } from '@multiformats/multiaddr' import { isBrowser } from 'wherearewe' import isPrivateIp from 'private-ip' import * as pkg from './version.js' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { codes } from './errors.js' import { isLoopback } from '@libp2p/utils/multiaddr/is-loopback' import type { Startable } from '@libp2p/interfaces/startable' @@ -94,7 +94,7 @@ export class NatManager implements Startable { this.gateway = init.gateway if (this.ttl < DEFAULT_TTL) { - throw errCode(new Error(`NatManager ttl should be at least ${DEFAULT_TTL} seconds`), codes.ERR_INVALID_PARAMETERS) + throw new CodeError(`NatManager ttl should be at least ${DEFAULT_TTL} seconds`, codes.ERR_INVALID_PARAMETERS) } } diff --git a/src/peer-routing.ts b/src/peer-routing.ts index 6e5246e6a3..20ec6677cd 100644 --- a/src/peer-routing.ts +++ b/src/peer-routing.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { codes, messages } from './errors.js' import { storeAddresses, @@ -141,11 +141,11 @@ export class DefaultPeerRouting implements PeerRouting, Startable { */ async findPeer (id: PeerId, options?: AbortOptions): Promise { if (this.routers.length === 0) { - throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE) + throw new CodeError('No peer routers available', codes.ERR_NO_ROUTERS_AVAILABLE) } if (id.toString() === this.components.peerId.toString()) { - throw errCode(new Error('Should not try to find self'), codes.ERR_FIND_SELF) + throw new CodeError('Should not try to find self', codes.ERR_FIND_SELF) } const output = await pipe( @@ -167,7 +167,7 @@ export class DefaultPeerRouting implements PeerRouting, Startable { return output } - throw errCode(new Error(messages.NOT_FOUND), codes.ERR_NOT_FOUND) + throw new CodeError(messages.NOT_FOUND, codes.ERR_NOT_FOUND) } /** @@ -175,7 +175,7 @@ export class DefaultPeerRouting implements PeerRouting, Startable { */ async * getClosestPeers (key: Uint8Array, options?: AbortOptions): AsyncIterable { if (this.routers.length === 0) { - throw errCode(new Error('No peer routers available'), codes.ERR_NO_ROUTERS_AVAILABLE) + throw new CodeError('No peer routers available', codes.ERR_NO_ROUTERS_AVAILABLE) } yield * pipe( diff --git a/src/ping/index.ts b/src/ping/index.ts index 35f665e97a..7f233298d2 100644 --- a/src/ping/index.ts +++ b/src/ping/index.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { codes } from '../errors.js' import { randomBytes } from '@libp2p/crypto' import { pipe } from 'it-pipe' @@ -119,7 +119,7 @@ export class PingService implements Startable { const end = Date.now() if (result == null || !uint8ArrayEquals(data, result.subarray())) { - throw errCode(new Error('Received wrong ping ack'), codes.ERR_WRONG_PING_ACK) + throw new CodeError('Received wrong ping ack', codes.ERR_WRONG_PING_ACK) } return end - start diff --git a/src/pnet/index.ts b/src/pnet/index.ts index da364de961..b40247367e 100644 --- a/src/pnet/index.ts +++ b/src/pnet/index.ts @@ -24,7 +24,7 @@ import { logger } from '@libp2p/logger' import { pipe } from 'it-pipe' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { duplexPair } from 'it-pair/duplex' import { randomBytes } from '@libp2p/crypto' import * as Errors from './errors.js' @@ -81,7 +81,7 @@ class PreSharedKeyConnectionProtector implements ConnectionProtector { } if (connection == null) { - throw errCode(new Error(Errors.NO_HANDSHAKE_CONNECTION), codes.ERR_INVALID_PARAMETERS) + throw new CodeError(Errors.NO_HANDSHAKE_CONNECTION, codes.ERR_INVALID_PARAMETERS) } // Exchange nonces @@ -94,7 +94,7 @@ class PreSharedKeyConnectionProtector implements ConnectionProtector { const result = await shake.reader.next(NONCE_LENGTH) if (result.value == null) { - throw errCode(new Error(Errors.STREAM_ENDED), codes.ERR_INVALID_PARAMETERS) + throw new CodeError(Errors.STREAM_ENDED, codes.ERR_INVALID_PARAMETERS) } const remoteNonce = result.value.slice() diff --git a/src/pubsub/dummy-pubsub.ts b/src/pubsub/dummy-pubsub.ts index 3334dee8f1..d104a5b501 100644 --- a/src/pubsub/dummy-pubsub.ts +++ b/src/pubsub/dummy-pubsub.ts @@ -1,7 +1,7 @@ import { EventEmitter } from '@libp2p/interfaces/events' import type { PeerId } from '@libp2p/interface-peer-id' import type { PublishResult, PubSub, PubSubEvents, StrictNoSign, StrictSign, TopicValidatorFn } from '@libp2p/interface-pubsub' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { messages, codes } from '../errors.js' export class DummyPubSub extends EventEmitter implements PubSub { @@ -20,34 +20,34 @@ export class DummyPubSub extends EventEmitter implements PubSub { } get globalSignaturePolicy (): typeof StrictSign | typeof StrictNoSign { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } get multicodecs (): string[] { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } getPeers (): PeerId[] { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } getTopics (): string[] { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } subscribe (): void { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } unsubscribe (): void { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } getSubscribers (): PeerId[] { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } async publish (): Promise { - throw errCode(new Error(messages.PUBSUB_DISABLED), codes.ERR_PUBSUB_DISABLED) + throw new CodeError(messages.PUBSUB_DISABLED, codes.ERR_PUBSUB_DISABLED) } } diff --git a/src/registrar.ts b/src/registrar.ts index b41c14174b..ea0ee5cae7 100644 --- a/src/registrar.ts +++ b/src/registrar.ts @@ -1,5 +1,5 @@ import { logger } from '@libp2p/logger' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { codes } from './errors.js' import { isTopology, StreamHandlerOptions, StreamHandlerRecord } from '@libp2p/interface-registrar' import merge from 'merge-options' @@ -55,7 +55,7 @@ export class DefaultRegistrar implements Registrar { const handler = this.handlers.get(protocol) if (handler == null) { - throw errCode(new Error(`No handler registered for protocol ${protocol}`), codes.ERR_NO_HANDLER_FOR_PROTOCOL) + throw new CodeError(`No handler registered for protocol ${protocol}`, codes.ERR_NO_HANDLER_FOR_PROTOCOL) } return handler @@ -78,7 +78,7 @@ export class DefaultRegistrar implements Registrar { */ async handle (protocol: string, handler: StreamHandler, opts?: StreamHandlerOptions): Promise { if (this.handlers.has(protocol)) { - throw errCode(new Error(`Handler already registered for protocol ${protocol}`), codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED) + throw new CodeError(`Handler already registered for protocol ${protocol}`, codes.ERR_PROTOCOL_HANDLER_ALREADY_REGISTERED) } const options = merge.bind({ ignoreUndefined: true })({ @@ -116,7 +116,7 @@ export class DefaultRegistrar implements Registrar { async register (protocol: string, topology: Topology): Promise { if (!isTopology(topology)) { log.error('topology must be an instance of interfaces/topology') - throw errCode(new Error('topology must be an instance of interfaces/topology'), codes.ERR_INVALID_PARAMETERS) + throw new CodeError('topology must be an instance of interfaces/topology', codes.ERR_INVALID_PARAMETERS) } // Create topology diff --git a/src/transport-manager.ts b/src/transport-manager.ts index 288796d1f0..7ed1609e23 100644 --- a/src/transport-manager.ts +++ b/src/transport-manager.ts @@ -1,6 +1,6 @@ import { logger } from '@libp2p/logger' import { codes } from './errors.js' -import errCode from 'err-code' +import { CodeError } from '@libp2p/interfaces/errors' import { FaultTolerance } from '@libp2p/interface-transport' import type { Listener, Transport, TransportManager, TransportManagerEvents, Upgrader } from '@libp2p/interface-transport' import type { Multiaddr } from '@multiformats/multiaddr' @@ -51,11 +51,11 @@ export class DefaultTransportManager extends EventEmitter r.status === 'fulfilled') if ((isListening == null) && this.faultTolerance !== FaultTolerance.NO_FATAL) { - throw errCode(new Error(`Transport (${key}) could not listen on any available address`), codes.ERR_NO_VALID_ADDRESSES) + throw new CodeError(`Transport (${key}) could not listen on any available address`, codes.ERR_NO_VALID_ADDRESSES) } } @@ -233,7 +233,7 @@ export class DefaultTransportManager extends EventEmitter implements Upg const accept = await this.components.connectionManager.acceptIncomingConnection(maConn) if (!accept) { - throw errCode(new Error('connection denied'), codes.ERR_CONNECTION_DENIED) + throw new CodeError('connection denied', codes.ERR_CONNECTION_DENIED) } let encryptedConn @@ -158,7 +158,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg maConn.sink = abortableStream.sink if ((await this.components.connectionGater.denyInboundConnection?.(maConn)) === true) { - throw errCode(new Error('The multiaddr connection is blocked by gater.acceptConnection'), codes.ERR_CONNECTION_INTERCEPTED) + throw new CodeError('The multiaddr connection is blocked by gater.acceptConnection', codes.ERR_CONNECTION_INTERCEPTED) } this.components.metrics?.trackMultiaddrConnection(maConn) @@ -191,13 +191,13 @@ export class DefaultUpgrader extends EventEmitter implements Upg ...protectedConn, ...encryptedConn })) === true) { - throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED) + throw new CodeError('The multiaddr connection is blocked by gater.acceptEncryptedConnection', codes.ERR_CONNECTION_INTERCEPTED) } } else { const idStr = maConn.remoteAddr.getPeerId() if (idStr == null) { - throw errCode(new Error('inbound connection that skipped encryption must have a peer id'), codes.ERR_INVALID_MULTIADDR) + throw new CodeError('inbound connection that skipped encryption must have a peer id', codes.ERR_INVALID_MULTIADDR) } const remotePeerId = peerIdFromString(idStr) @@ -227,7 +227,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg ...protectedConn, ...encryptedConn })) === true) { - throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED) + throw new CodeError('The multiaddr connection is blocked by gater.acceptEncryptedConnection', codes.ERR_CONNECTION_INTERCEPTED) } log('Successfully upgraded inbound connection') @@ -257,7 +257,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg remotePeerId = peerIdFromString(idStr) if ((await this.components.connectionGater.denyOutboundConnection?.(remotePeerId, maConn)) === true) { - throw errCode(new Error('The multiaddr connection is blocked by connectionGater.denyOutboundConnection'), codes.ERR_CONNECTION_INTERCEPTED) + throw new CodeError('The multiaddr connection is blocked by connectionGater.denyOutboundConnection', codes.ERR_CONNECTION_INTERCEPTED) } } @@ -298,11 +298,11 @@ export class DefaultUpgrader extends EventEmitter implements Upg ...protectedConn, ...encryptedConn })) === true) { - throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED) + throw new CodeError('The multiaddr connection is blocked by gater.acceptEncryptedConnection', codes.ERR_CONNECTION_INTERCEPTED) } } else { if (remotePeerId == null) { - throw errCode(new Error('Encryption was skipped but no peer id was passed'), codes.ERR_INVALID_PEER) + throw new CodeError('Encryption was skipped but no peer id was passed', codes.ERR_INVALID_PEER) } cryptoProtocol = 'native' @@ -331,7 +331,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg ...protectedConn, ...encryptedConn })) === true) { - throw errCode(new Error('The multiaddr connection is blocked by gater.acceptEncryptedConnection'), codes.ERR_CONNECTION_INTERCEPTED) + throw new CodeError('The multiaddr connection is blocked by gater.acceptEncryptedConnection', codes.ERR_CONNECTION_INTERCEPTED) } log('Successfully upgraded outbound connection') @@ -387,7 +387,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg const streamCount = countStreams(protocol, 'inbound', connection) if (streamCount === incomingLimit) { - muxedStream.abort(errCode(new Error(`Too many inbound protocol streams for protocol "${protocol}" - limit ${incomingLimit}`), codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS)) + muxedStream.abort(new CodeError(`Too many inbound protocol streams for protocol "${protocol}" - limit ${incomingLimit}`, codes.ERR_TOO_MANY_INBOUND_PROTOCOL_STREAMS)) return } @@ -423,7 +423,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg newStream = async (protocols: string[], options: AbortOptions = {}): Promise => { if (muxer == null) { - throw errCode(new Error('Stream is not multiplexed'), codes.ERR_MUXER_UNAVAILABLE) + throw new CodeError('Stream is not multiplexed', codes.ERR_MUXER_UNAVAILABLE) } log('%s: starting new stream on %s', direction, protocols) @@ -449,7 +449,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg const streamCount = countStreams(protocol, 'outbound', connection) if (streamCount === outgoingLimit) { - const err = errCode(new Error(`Too many outbound protocol streams for protocol "${protocol}" - limit ${outgoingLimit}`), codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS) + const err = new CodeError(`Too many outbound protocol streams for protocol "${protocol}" - limit ${outgoingLimit}`, codes.ERR_TOO_MANY_OUTBOUND_PROTOCOL_STREAMS) muxedStream.abort(err) throw err @@ -479,7 +479,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg throw err } - throw errCode(err, codes.ERR_UNSUPPORTED_PROTOCOL) + throw new CodeError(String(err), codes.ERR_UNSUPPORTED_PROTOCOL) } finally { if (controller != null) { controller.clear() @@ -524,7 +524,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg maConn.timeline.upgraded = Date.now() const errConnectionNotMultiplexed = (): any => { - throw errCode(new Error('connection is not multiplexed'), codes.ERR_CONNECTION_NOT_MULTIPLEXED) + throw new CodeError('connection is not multiplexed', codes.ERR_CONNECTION_NOT_MULTIPLEXED) } // Create the connection @@ -590,7 +590,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg protocol } } catch (err: any) { - throw errCode(err, codes.ERR_ENCRYPTION_FAILED) + throw new CodeError(String(err), codes.ERR_ENCRYPTION_FAILED) } } @@ -619,7 +619,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg protocol } } catch (err: any) { - throw errCode(err, codes.ERR_ENCRYPTION_FAILED) + throw new CodeError(String(err), codes.ERR_ENCRYPTION_FAILED) } } @@ -639,7 +639,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg return { stream, muxerFactory } } catch (err: any) { log.error('error multiplexing outbound stream', err) - throw errCode(err, codes.ERR_MUXER_UNAVAILABLE) + throw new CodeError(String(err), codes.ERR_MUXER_UNAVAILABLE) } } @@ -658,7 +658,7 @@ export class DefaultUpgrader extends EventEmitter implements Upg return { stream, muxerFactory } } catch (err: any) { log.error('error multiplexing inbound stream', err) - throw errCode(err, codes.ERR_MUXER_UNAVAILABLE) + throw new CodeError(String(err), codes.ERR_MUXER_UNAVAILABLE) } } }