Skip to content

Commit d7fa853

Browse files
tabcatachingbrain
andauthored
fix: replace err-code with CodeError (#1532)
Replaces [err-code](https://github.com/IndigoUnited/js-err-code/blob/master/index.js) with [CodeError](libp2p/js-libp2p-interfaces#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 <alex@achingbrain.net>
1 parent 5e63ee2 commit d7fa853

25 files changed

+137
-138
lines changed

package.json

+1-2
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@
121121
"@libp2p/interface-registrar": "^2.0.3",
122122
"@libp2p/interface-stream-muxer": "^3.0.0",
123123
"@libp2p/interface-transport": "^2.1.0",
124-
"@libp2p/interfaces": "^3.0.3",
124+
"@libp2p/interfaces": "^3.2.0",
125125
"@libp2p/keychain": "^2.0.0",
126126
"@libp2p/logger": "^2.0.1",
127127
"@libp2p/multistream-select": "^3.0.0",
@@ -138,7 +138,6 @@
138138
"abortable-iterator": "^4.0.2",
139139
"any-signal": "^3.0.0",
140140
"datastore-core": "^9.0.0",
141-
"err-code": "^3.0.1",
142141
"interface-datastore": "^8.0.0",
143142
"it-all": "^2.0.0",
144143
"it-drain": "^2.0.0",

src/circuit/transport/index.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import { StopMessage, HopMessage, Status } from '../pb/index.js'
22
import { logger } from '@libp2p/logger'
3-
import createError from 'err-code'
43
import * as mafmt from '@multiformats/mafmt'
54
import { multiaddr } from '@multiformats/multiaddr'
65
import { codes } from '../../errors.js'
@@ -23,6 +22,7 @@ import type { ContentRouting } from '@libp2p/interface-content-routing'
2322
import { CIRCUIT_PROTO_CODE, RELAY_V2_HOP_CODEC, RELAY_V2_STOP_CODEC } from '../constants.js'
2423
import { RelayStoreInit, ReservationStore } from './reservation-store.js'
2524
import { RelayDiscovery, RelayDiscoveryComponents } from './discovery.js'
25+
import { CodeError } from '@libp2p/interfaces/errors'
2626

2727
const log = logger('libp2p:circuit-relay:transport')
2828

@@ -154,7 +154,7 @@ class CircuitRelayTransport implements Transport {
154154
if (ma.protoCodes().filter(code => code === CIRCUIT_PROTO_CODE).length !== 1) {
155155
const errMsg = 'Invalid circuit relay address'
156156
log.error(errMsg, ma)
157-
throw createError(new Error(errMsg), codes.ERR_RELAYED_DIAL)
157+
throw new CodeError(errMsg, codes.ERR_RELAYED_DIAL)
158158
}
159159

160160
// Check the multiaddr to see if it contains a relay and a destination peer
@@ -167,7 +167,7 @@ class CircuitRelayTransport implements Transport {
167167
if (relayId == null || destinationId == null) {
168168
const errMsg = 'Circuit relay dial failed as addresses did not have peer id'
169169
log.error(errMsg)
170-
throw createError(new Error(errMsg), codes.ERR_RELAYED_DIAL)
170+
throw new CodeError(errMsg, codes.ERR_RELAYED_DIAL)
171171
}
172172

173173
const relayPeer = peerIdFromString(relayId)
@@ -223,7 +223,7 @@ class CircuitRelayTransport implements Transport {
223223
const status = await hopstr.read()
224224

225225
if (status.status !== Status.OK) {
226-
throw createError(new Error(`failed to connect via relay with status ${status?.status?.toString() ?? 'undefined'}`), codes.ERR_HOP_REQUEST_FAILED)
226+
throw new CodeError(`failed to connect via relay with status ${status?.status?.toString() ?? 'undefined'}`, codes.ERR_HOP_REQUEST_FAILED)
227227
}
228228

229229
// TODO: do something with limit and transient connection

src/components.ts

+13-13
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import errCode from 'err-code'
1+
import { CodeError } from '@libp2p/interfaces/errors'
22
import type { ConnectionProtector } from '@libp2p/interface-connection'
33
import type { ContentRouting } from '@libp2p/interface-content-routing'
44
import type { AddressManager } from '@libp2p/interface-address-manager'
@@ -157,7 +157,7 @@ export class DefaultComponents implements Components, Startable {
157157

158158
get peerId (): PeerId {
159159
if (this._peerId == null) {
160-
throw errCode(new Error('peerId not set'), 'ERR_SERVICE_MISSING')
160+
throw new CodeError('peerId not set', 'ERR_SERVICE_MISSING')
161161
}
162162

163163
return this._peerId
@@ -169,7 +169,7 @@ export class DefaultComponents implements Components, Startable {
169169

170170
get addressManager (): AddressManager {
171171
if (this._addressManager == null) {
172-
throw errCode(new Error('addressManager not set'), 'ERR_SERVICE_MISSING')
172+
throw new CodeError('addressManager not set', 'ERR_SERVICE_MISSING')
173173
}
174174

175175
return this._addressManager
@@ -181,7 +181,7 @@ export class DefaultComponents implements Components, Startable {
181181

182182
get peerStore (): PeerStore {
183183
if (this._peerStore == null) {
184-
throw errCode(new Error('peerStore not set'), 'ERR_SERVICE_MISSING')
184+
throw new CodeError('peerStore not set', 'ERR_SERVICE_MISSING')
185185
}
186186

187187
return this._peerStore
@@ -193,7 +193,7 @@ export class DefaultComponents implements Components, Startable {
193193

194194
get upgrader (): Upgrader {
195195
if (this._upgrader == null) {
196-
throw errCode(new Error('upgrader not set'), 'ERR_SERVICE_MISSING')
196+
throw new CodeError('upgrader not set', 'ERR_SERVICE_MISSING')
197197
}
198198

199199
return this._upgrader
@@ -205,7 +205,7 @@ export class DefaultComponents implements Components, Startable {
205205

206206
get registrar (): Registrar {
207207
if (this._registrar == null) {
208-
throw errCode(new Error('registrar not set'), 'ERR_SERVICE_MISSING')
208+
throw new CodeError('registrar not set', 'ERR_SERVICE_MISSING')
209209
}
210210

211211
return this._registrar
@@ -217,7 +217,7 @@ export class DefaultComponents implements Components, Startable {
217217

218218
get connectionManager (): ConnectionManager {
219219
if (this._connectionManager == null) {
220-
throw errCode(new Error('connectionManager not set'), 'ERR_SERVICE_MISSING')
220+
throw new CodeError('connectionManager not set', 'ERR_SERVICE_MISSING')
221221
}
222222

223223
return this._connectionManager
@@ -229,7 +229,7 @@ export class DefaultComponents implements Components, Startable {
229229

230230
get transportManager (): TransportManager {
231231
if (this._transportManager == null) {
232-
throw errCode(new Error('transportManager not set'), 'ERR_SERVICE_MISSING')
232+
throw new CodeError('transportManager not set', 'ERR_SERVICE_MISSING')
233233
}
234234

235235
return this._transportManager
@@ -241,7 +241,7 @@ export class DefaultComponents implements Components, Startable {
241241

242242
get connectionGater (): ConnectionGater {
243243
if (this._connectionGater == null) {
244-
throw errCode(new Error('connectionGater not set'), 'ERR_SERVICE_MISSING')
244+
throw new CodeError('connectionGater not set', 'ERR_SERVICE_MISSING')
245245
}
246246

247247
return this._connectionGater
@@ -253,7 +253,7 @@ export class DefaultComponents implements Components, Startable {
253253

254254
get contentRouting (): ContentRouting {
255255
if (this._contentRouting == null) {
256-
throw errCode(new Error('contentRouting not set'), 'ERR_SERVICE_MISSING')
256+
throw new CodeError('contentRouting not set', 'ERR_SERVICE_MISSING')
257257
}
258258

259259
return this._contentRouting
@@ -265,7 +265,7 @@ export class DefaultComponents implements Components, Startable {
265265

266266
get peerRouting (): PeerRouting {
267267
if (this._peerRouting == null) {
268-
throw errCode(new Error('peerRouting not set'), 'ERR_SERVICE_MISSING')
268+
throw new CodeError('peerRouting not set', 'ERR_SERVICE_MISSING')
269269
}
270270

271271
return this._peerRouting
@@ -277,7 +277,7 @@ export class DefaultComponents implements Components, Startable {
277277

278278
get datastore (): Datastore {
279279
if (this._datastore == null) {
280-
throw errCode(new Error('datastore not set'), 'ERR_SERVICE_MISSING')
280+
throw new CodeError('datastore not set', 'ERR_SERVICE_MISSING')
281281
}
282282

283283
return this._datastore
@@ -297,7 +297,7 @@ export class DefaultComponents implements Components, Startable {
297297

298298
get dialer (): Dialer {
299299
if (this._dialer == null) {
300-
throw errCode(new Error('dialer not set'), 'ERR_SERVICE_MISSING')
300+
throw new CodeError('dialer not set', 'ERR_SERVICE_MISSING')
301301
}
302302

303303
return this._dialer

src/config.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import { FaultTolerance } from '@libp2p/interface-transport'
77
import type { Multiaddr } from '@multiformats/multiaddr'
88
import type { Libp2pInit } from './index.js'
99
import { codes, messages } from './errors.js'
10-
import errCode from 'err-code'
10+
import { CodeError } from '@libp2p/interfaces/errors'
1111
import type { RecursivePartial } from '@libp2p/interfaces'
1212
import { isNode, isBrowser, isWebWorker, isElectronMain, isElectronRenderer, isReactNative } from 'wherearewe'
1313

@@ -92,15 +92,15 @@ export function validateConfig (opts: RecursivePartial<Libp2pInit>): Libp2pInit
9292
const resultingOptions: Libp2pInit = mergeOptions(DefaultConfig, opts)
9393

9494
if (resultingOptions.transports == null || resultingOptions.transports.length < 1) {
95-
throw errCode(new Error(messages.ERR_TRANSPORTS_REQUIRED), codes.ERR_TRANSPORTS_REQUIRED)
95+
throw new CodeError(messages.ERR_TRANSPORTS_REQUIRED, codes.ERR_TRANSPORTS_REQUIRED)
9696
}
9797

9898
if (resultingOptions.connectionEncryption == null || resultingOptions.connectionEncryption.length === 0) {
99-
throw errCode(new Error(messages.CONN_ENCRYPTION_REQUIRED), codes.CONN_ENCRYPTION_REQUIRED)
99+
throw new CodeError(messages.CONN_ENCRYPTION_REQUIRED, codes.CONN_ENCRYPTION_REQUIRED)
100100
}
101101

102102
if (resultingOptions.connectionProtector === null && globalThis.process?.env?.LIBP2P_FORCE_PNET != null) { // eslint-disable-line no-undef
103-
throw errCode(new Error(messages.ERR_PROTECTOR_REQUIRED), codes.ERR_PROTECTOR_REQUIRED)
103+
throw new CodeError(messages.ERR_PROTECTOR_REQUIRED, codes.ERR_PROTECTOR_REQUIRED)
104104
}
105105

106106
// Append user agent version to default AGENT_VERSION depending on the environment

src/connection-manager/dialer/dial-request.ts

+5-5
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import errCode from 'err-code'
1+
import { CodeError } from '@libp2p/interfaces/errors'
22
import { anySignal } from 'any-signal'
33
import FIFO from 'p-fifo'
44
import { setMaxListeners } from 'events'
@@ -50,7 +50,7 @@ export class DialRequest {
5050

5151
// If no tokens are available, throw
5252
if (tokens.length < 1) {
53-
throw errCode(new Error('No dial tokens available'), codes.ERR_NO_DIAL_TOKENS)
53+
throw new CodeError('No dial tokens available', codes.ERR_NO_DIAL_TOKENS)
5454
}
5555

5656
const tokenHolder = new FIFO<number>()
@@ -87,12 +87,12 @@ export class DialRequest {
8787
// End attempt once another attempt succeeded
8888
if (done) {
8989
this.dialer.releaseToken(tokens.splice(tokens.indexOf(token), 1)[0])
90-
throw errCode(new Error('dialAction already succeeded'), codes.ERR_ALREADY_SUCCEEDED)
90+
throw new CodeError('dialAction already succeeded', codes.ERR_ALREADY_SUCCEEDED)
9191
}
9292

9393
const controller = dialAbortControllers[i]
9494
if (controller == null) {
95-
throw errCode(new Error('dialAction did not come with an AbortController'), codes.ERR_INVALID_PARAMETERS)
95+
throw new CodeError('dialAction did not come with an AbortController', codes.ERR_INVALID_PARAMETERS)
9696
}
9797
let conn
9898
try {
@@ -116,7 +116,7 @@ export class DialRequest {
116116
// Notify Promise.any that attempt was not successful
117117
// to prevent from returning undefined despite there
118118
// were successful dial attempts
119-
throw errCode(new Error('dialAction led to empty object'), codes.ERR_TRANSPORT_DIAL_FAILED)
119+
throw new CodeError('dialAction led to empty object', codes.ERR_TRANSPORT_DIAL_FAILED)
120120
} else {
121121
// This dial succeeded, don't attempt anything else
122122
done = true

src/connection-manager/dialer/index.ts

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { logger } from '@libp2p/logger'
2-
import errCode from 'err-code'
2+
import { CodeError } from '@libp2p/interfaces/errors'
33
import { isMultiaddr, Multiaddr, Resolver, multiaddr, resolvers } from '@multiformats/multiaddr'
44
import { TimeoutController } from 'timeout-abort-controller'
55
import { anySignal } from 'any-signal'
@@ -156,7 +156,7 @@ export class DefaultDialer implements Startable, Dialer {
156156

157157
if (peerId != null) {
158158
if (this.components.peerId.equals(peerId)) {
159-
throw errCode(new Error('Tried to dial self'), codes.ERR_DIALED_SELF)
159+
throw new CodeError('Tried to dial self', codes.ERR_DIALED_SELF)
160160
}
161161

162162
if (multiaddr != null) {
@@ -165,7 +165,7 @@ export class DefaultDialer implements Startable, Dialer {
165165
}
166166

167167
if ((await this.components.connectionGater.denyDialPeer?.(peerId)) === true) {
168-
throw errCode(new Error('The dial request is blocked by gater.allowDialPeer'), codes.ERR_PEER_DIAL_INTERCEPTED)
168+
throw new CodeError('The dial request is blocked by gater.allowDialPeer', codes.ERR_PEER_DIAL_INTERCEPTED)
169169
}
170170
}
171171

@@ -195,7 +195,7 @@ export class DefaultDialer implements Startable, Dialer {
195195
}
196196

197197
if (dialTarget.addrs.length === 0) {
198-
throw errCode(new Error('The dial request has no valid addresses'), codes.ERR_NO_VALID_ADDRESSES)
198+
throw new CodeError('The dial request has no valid addresses', codes.ERR_NO_VALID_ADDRESSES)
199199
}
200200

201201
// try to join an in-flight dial for this peer if one is available
@@ -267,7 +267,7 @@ export class DefaultDialer implements Startable, Dialer {
267267
addrs = [...new Set(addrs.map(ma => ma.toString()))].map(ma => multiaddr(ma))
268268

269269
if (addrs.length > this.maxAddrsToDial) {
270-
throw errCode(new Error('dial with more addresses than allowed'), codes.ERR_TOO_MANY_ADDRESSES)
270+
throw new CodeError('dial with more addresses than allowed', codes.ERR_TOO_MANY_ADDRESSES)
271271
}
272272

273273
const peerId = isPeerId(peerIdOrMultiaddr.peerId) ? peerIdOrMultiaddr.peerId : undefined
@@ -324,7 +324,7 @@ export class DefaultDialer implements Startable, Dialer {
324324
*/
325325
const dialAction: DialAction = async (addr, options = {}) => {
326326
if (options.signal?.aborted === true) {
327-
throw errCode(new Error('already aborted'), codes.ERR_ALREADY_ABORTED)
327+
throw new CodeError('already aborted', codes.ERR_ALREADY_ABORTED)
328328
}
329329

330330
return await this.components.transportManager.dial(addr, options).catch(err => {

src/connection-manager/index.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { logger } from '@libp2p/logger'
2-
import errCode from 'err-code'
2+
import { CodeError } from '@libp2p/interfaces/errors'
33
import mergeOptions from 'merge-options'
44
import { LatencyMonitor, SummaryObject } from './latency-monitor.js'
55
import type { AbortOptions } from '@libp2p/interfaces'
@@ -163,7 +163,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
163163
this.opts = mergeOptions.call({ ignoreUndefined: true }, defaultOptions, init)
164164

165165
if (this.opts.maxConnections < this.opts.minConnections) {
166-
throw errCode(new Error('Connection Manager maxConnections must be greater than minConnections'), codes.ERR_INVALID_PARAMETERS)
166+
throw new CodeError('Connection Manager maxConnections must be greater than minConnections', codes.ERR_INVALID_PARAMETERS)
167167
}
168168

169169
log('options: %o', this.opts)
@@ -473,7 +473,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
473473
const { peerId, multiaddr } = getPeerAddress(peerIdOrMultiaddr)
474474

475475
if (peerId == null && multiaddr == null) {
476-
throw errCode(new TypeError('Can only open connections to PeerIds or Multiaddrs'), codes.ERR_INVALID_PARAMETERS)
476+
throw new CodeError('Can only open connections to PeerIds or Multiaddrs', codes.ERR_INVALID_PARAMETERS)
477477
}
478478

479479
if (peerId != null) {
@@ -547,7 +547,7 @@ export class DefaultConnectionManager extends EventEmitter<ConnectionManagerEven
547547
*/
548548
getAll (peerId: PeerId): Connection[] {
549549
if (!isPeerId(peerId)) {
550-
throw errCode(new Error('peerId must be an instance of peer-id'), codes.ERR_INVALID_PARAMETERS)
550+
throw new CodeError('peerId must be an instance of peer-id', codes.ERR_INVALID_PARAMETERS)
551551
}
552552

553553
const id = peerId.toString()

src/connection/index.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { Multiaddr } from '@multiformats/multiaddr'
2-
import errCode from 'err-code'
2+
import { CodeError } from '@libp2p/interfaces/errors'
33
import { OPEN, CLOSING, CLOSED } from '@libp2p/interface-connection/status'
44
import { symbol } from '@libp2p/interface-connection'
55
import type { Connection, ConnectionStat, Stream } from '@libp2p/interface-connection'
@@ -107,11 +107,11 @@ export class ConnectionImpl implements Connection {
107107
*/
108108
async newStream (protocols: string | string[], options?: AbortOptions): Promise<Stream> {
109109
if (this.stat.status === CLOSING) {
110-
throw errCode(new Error('the connection is being closed'), 'ERR_CONNECTION_BEING_CLOSED')
110+
throw new CodeError('the connection is being closed', 'ERR_CONNECTION_BEING_CLOSED')
111111
}
112112

113113
if (this.stat.status === CLOSED) {
114-
throw errCode(new Error('the connection is closed'), 'ERR_CONNECTION_CLOSED')
114+
throw new CodeError('the connection is closed', 'ERR_CONNECTION_CLOSED')
115115
}
116116

117117
if (!Array.isArray(protocols)) {

0 commit comments

Comments
 (0)