diff --git a/interop/hole-punching/hole_punching.nim b/interop/hole-punching/hole_punching.nim index 85dd91f21..45163026c 100644 --- a/interop/hole-punching/hole_punching.nim +++ b/interop/hole-punching/hole_punching.nim @@ -84,8 +84,8 @@ proc main() {.async.} = debug "Dialing relay...", relayMA let relayId = await switch.connect(relayMA).wait(30.seconds) debug "Connected to relay", relayId - except AsyncTimeoutError: - raise newException(CatchableError, "Connection to relay timed out") + except AsyncTimeoutError as e: + raise newException(CatchableError, "Connection to relay timed out: " & e.msg, e) # Wait for our relay address to be published while not switch.peerInfo.addrs.anyIt(it.contains(multiCodec("p2p-circuit")).tryGet()): @@ -103,7 +103,7 @@ proc main() {.async.} = try: PeerId.init(redisClient.bLPop(@["LISTEN_CLIENT_PEER_ID"], 0)[1]).tryGet() except Exception as e: - raise newException(CatchableError, e.msg) + raise newException(CatchableError, "Exception init peer: " & e.msg, e) debug "Got listener peer id", listenerId let listenerRelayAddr = MultiAddress.init($relayMA & "/p2p-circuit").tryGet() @@ -130,8 +130,8 @@ try: return "done" discard waitFor(mainAsync().wait(4.minutes)) -except AsyncTimeoutError: - error "Program execution timed out." +except AsyncTimeoutError as e: + error "Program execution timed out", description = e.msg quit(-1) except CatchableError as e: error "Unexpected error", description = e.msg diff --git a/interop/transport/main.nim b/interop/transport/main.nim index 6565e1d14..897ee4759 100644 --- a/interop/transport/main.nim +++ b/interop/transport/main.nim @@ -80,7 +80,7 @@ proc main() {.async.} = try: redisClient.bLPop(@["listenerAddr"], testTimeout.seconds.int)[1] except Exception as e: - raise newException(CatchableError, e.msg) + raise newException(CatchableError, "Exception calling bLPop: " & e.msg, e) let remoteAddr = MultiAddress.init(listenerAddr).tryGet() dialingStart = Moment.now() @@ -105,8 +105,8 @@ try: return "done" discard waitFor(mainAsync().wait(testTimeout)) -except AsyncTimeoutError: - error "Program execution timed out." +except AsyncTimeoutError as e: + error "Program execution timed out", description = e.msg quit(-1) except CatchableError as e: error "Unexpected error", description = e.msg diff --git a/libp2p/connmanager.nim b/libp2p/connmanager.nim index d31c9d740..ddbf93ecb 100644 --- a/libp2p/connmanager.nim +++ b/libp2p/connmanager.nim @@ -140,7 +140,7 @@ proc triggerConnEvent*( except CancelledError as exc: raise exc except CatchableError as exc: - warn "Exception in triggerConnEvents", + warn "Exception in triggerConnEvent", description = exc.msg, peer = peerId, event = $event proc addPeerEventHandler*( @@ -186,7 +186,7 @@ proc expectConnection*( if key in c.expectedConnectionsOverLimit: raise newException( AlreadyExpectingConnectionError, - "Already expecting an incoming connection from that peer", + "Already expecting an incoming connection from that peer: " & shortLog(p), ) let future = Future[Muxer].Raising([CancelledError]).init() diff --git a/libp2p/crypto/secp.nim b/libp2p/crypto/secp.nim index 7fa3c187b..051d905ea 100644 --- a/libp2p/crypto/secp.nim +++ b/libp2p/crypto/secp.nim @@ -85,8 +85,9 @@ proc init*(sig: var SkSignature, data: string): SkResult[void] = var buffer: seq[byte] try: buffer = hexToSeqByte(data) - except ValueError: - return err("secp: Hex to bytes failed") + except ValueError as e: + let errMsg = "secp: Hex to bytes failed: " & e.msg + return err(errMsg.cstring) init(sig, buffer) proc init*(t: typedesc[SkPrivateKey], data: openArray[byte]): SkResult[SkPrivateKey] = diff --git a/libp2p/daemon/daemonapi.nim b/libp2p/daemon/daemonapi.nim index 70da9b778..3b079a6a6 100644 --- a/libp2p/daemon/daemonapi.nim +++ b/libp2p/daemon/daemonapi.nim @@ -595,13 +595,13 @@ template exceptionToAssert(body: untyped): untyped = try: res = body except OSError as exc: - raise exc + raise newException(OSError, "failure in exceptionToAssert: " & exc.msg, exc) except IOError as exc: - raise exc + raise newException(IOError, "failure in exceptionToAssert: " & exc.msg, exc) except Defect as exc: - raise exc + raise newException(Defect, "failure in exceptionToAssert: " & exc.msg, exc) except Exception as exc: - raiseAssert exc.msg + raiseAssert "Exception captured in exceptionToAssert: " & exc.msg when defined(nimHasWarnBareExcept): {.pop.} res @@ -967,9 +967,9 @@ proc openStream*( stream.flags.incl(Outbound) stream.transp = transp result = stream - except ResultError[ProtoError]: + except ResultError[ProtoError] as e: await api.closeConnection(transp) - raise newException(DaemonLocalError, "Wrong message type!") + raise newException(DaemonLocalError, "Wrong message type: " & e.msg, e) proc streamHandler(server: StreamServer, transp: StreamTransport) {.async.} = # must not specify raised exceptions as this is StreamCallback from chronos @@ -1023,10 +1023,10 @@ proc addHandler*( api.servers.add(P2PServer(server: server, address: maddress)) except DaemonLocalError as e: await removeHandler() - raise e + raise newException(DaemonLocalError, "Could not add stream handler: " & e.msg, e) except TransportError as e: await removeHandler() - raise e + raise newException(TransportError, "Could not add stream handler: " & e.msg, e) except CancelledError as e: await removeHandler() raise e @@ -1503,10 +1503,14 @@ proc pubsubSubscribe*( result = ticket except DaemonLocalError as exc: await api.closeConnection(transp) - raise exc + raise newException( + DaemonLocalError, "Could not subscribe to topic '" & topic & "': " & exc.msg, exc + ) except TransportError as exc: await api.closeConnection(transp) - raise exc + raise newException( + TransportError, "Could not subscribe to topic '" & topic & "': " & exc.msg, exc + ) except CancelledError as exc: await api.closeConnection(transp) raise exc diff --git a/libp2p/dialer.nim b/libp2p/dialer.nim index ecb45bc12..d352d9a6f 100644 --- a/libp2p/dialer.nim +++ b/libp2p/dialer.nim @@ -127,8 +127,8 @@ proc expandDnsAddr( var peerIdBytes: seq[byte] try: peerIdBytes = lastPart.protoArgument().tryGet() - except ResultError[string]: - raiseAssert "expandDnsAddr failed in protoArgument: " & getCurrentExceptionMsg() + except ResultError[string] as e: + raiseAssert "expandDnsAddr failed in expandDnsAddr protoArgument: " & e.msg let addrPeerId = PeerId.init(peerIdBytes).tryGet() result.add((resolvedAddress[0 ..^ 2].tryGet(), Opt.some(addrPeerId))) @@ -178,7 +178,7 @@ proc internalConnect( dir = Direction.Out, ): Future[Muxer] {.async: (raises: [DialFailedError, CancelledError]).} = if Opt.some(self.localPeerId) == peerId: - raise newException(DialFailedError, "can't dial self!") + raise newException(DialFailedError, "internalConnect can't dial self!") # Ensure there's only one in-flight attempt per peer let lock = self.dialLock.mgetOrPut(peerId.get(default(PeerId)), newAsyncLock()) @@ -186,8 +186,8 @@ proc internalConnect( defer: try: lock.release() - except AsyncLockError: - raiseAssert "lock must have been acquired in line above" + except AsyncLockError as e: + raiseAssert "lock must have been acquired in line above: " & e.msg if reuseConnection: peerId.withValue(peerId): @@ -198,7 +198,9 @@ proc internalConnect( try: self.connManager.getOutgoingSlot(forceDial) except TooManyConnectionsError as exc: - raise newException(DialFailedError, exc.msg) + raise newException( + DialFailedError, "failed getOutgoingSlot in internalConnect: " & exc.msg, exc + ) let muxed = try: @@ -208,11 +210,15 @@ proc internalConnect( raise exc except CatchableError as exc: slot.release() - raise newException(DialFailedError, exc.msg) + raise newException( + DialFailedError, "failed dialAndUpgrade in internalConnect: " & exc.msg, exc + ) slot.trackMuxer(muxed) if isNil(muxed): # None of the addresses connected - raise newException(DialFailedError, "Unable to establish outgoing link") + raise newException( + DialFailedError, "Unable to establish outgoing link in internalConnect" + ) try: self.connManager.storeMuxer(muxed) @@ -228,7 +234,11 @@ proc internalConnect( except CatchableError as exc: trace "Failed to finish outgoing upgrade", description = exc.msg await muxed.close() - raise newException(DialFailedError, "Failed to finish outgoing upgrade") + raise newException( + DialFailedError, + "Failed to finish outgoing upgrade in internalConnect: " & exc.msg, + exc, + ) method connect*( self: Dialer, @@ -260,7 +270,7 @@ method connect*( if allowUnknownPeerId == false: raise newException( - DialFailedError, "Address without PeerID and unknown peer id disabled!" + DialFailedError, "Address without PeerID and unknown peer id disabled in connect" ) return @@ -273,7 +283,7 @@ proc negotiateStream( let selected = await MultistreamSelect.select(conn, protos) if not protos.contains(selected): await conn.closeWithEOF() - raise newException(DialFailedError, "Unable to select sub-protocol " & $protos) + raise newException(DialFailedError, "Unable to select sub-protocol: " & $protos) return conn @@ -289,13 +299,13 @@ method tryDial*( try: let mux = await self.dialAndUpgrade(Opt.some(peerId), addrs) if mux.isNil(): - raise newException(DialFailedError, "No valid multiaddress") + raise newException(DialFailedError, "No valid multiaddress in tryDial") await mux.close() return mux.connection.observedAddr except CancelledError as exc: raise exc except CatchableError as exc: - raise newException(DialFailedError, exc.msg) + raise newException(DialFailedError, "tryDial failed: " & exc.msg, exc) method dial*( self: Dialer, peerId: PeerId, protos: seq[string] @@ -309,14 +319,17 @@ method dial*( try: let stream = await self.connManager.getStream(peerId) if stream.isNil: - raise newException(DialFailedError, "Couldn't get muxed stream") + raise newException( + DialFailedError, + "Couldn't get muxed stream in dial for peer_id: " & shortLog(peerId), + ) return await self.negotiateStream(stream, protos) except CancelledError as exc: - trace "Dial canceled" + trace "Dial canceled", description = exc.msg raise exc except CatchableError as exc: trace "Error dialing", description = exc.msg - raise newException(DialFailedError, exc.msg) + raise newException(DialFailedError, "failed dial existing: " & exc.msg) method dial*( self: Dialer, @@ -347,17 +360,20 @@ method dial*( stream = await self.connManager.getStream(conn) if isNil(stream): - raise newException(DialFailedError, "Couldn't get muxed stream") + raise newException( + DialFailedError, + "Couldn't get muxed stream in new dial for remote_peer_id: " & shortLog(peerId), + ) return await self.negotiateStream(stream, protos) except CancelledError as exc: - trace "Dial canceled", conn + trace "Dial canceled", conn, description = exc.msg await cleanup() raise exc except CatchableError as exc: debug "Error dialing", conn, description = exc.msg await cleanup() - raise newException(DialFailedError, exc.msg) + raise newException(DialFailedError, "failed new dial: " & exc.msg, exc) method addTransport*(self: Dialer, t: Transport) = self.transports &= t diff --git a/libp2p/discovery/discoverymngr.nim b/libp2p/discovery/discoverymngr.nim index ee31d6b50..012102f50 100644 --- a/libp2p/discovery/discoverymngr.nim +++ b/libp2p/discovery/discoverymngr.nim @@ -113,7 +113,7 @@ proc add*(dm: DiscoveryManager, di: DiscoveryInterface) = try: query.peers.putNoWait(pa) except AsyncQueueFullError as exc: - debug "Cannot push discovered peer to queue" + debug "Cannot push discovered peer to queue", description = exc.msg proc request*(dm: DiscoveryManager, pa: PeerAttributes): DiscoveryQuery = var query = DiscoveryQuery(attr: pa, peers: newAsyncQueue[PeerAttributes]()) diff --git a/libp2p/multihash.nim b/libp2p/multihash.nim index 8a7dee266..bd6a2ae5b 100644 --- a/libp2p/multihash.nim +++ b/libp2p/multihash.nim @@ -567,7 +567,7 @@ proc init*(mhtype: typedesc[MultiHash], data: string): MhResult[MultiHash] {.inl proc init58*(mhtype: typedesc[MultiHash], data: string): MultiHash {.inline.} = ## Create MultiHash from BASE58 encoded string representation ``data``. if MultiHash.decode(Base58.decode(data), result) == -1: - raise newException(MultihashError, "Incorrect MultiHash binary format") + raise newException(MultihashError, "Incorrect MultiHash binary format in init58") proc cmp(a: openArray[byte], b: openArray[byte]): bool {.inline.} = if len(a) != len(b): diff --git a/libp2p/muxers/mplex/lpchannel.nim b/libp2p/muxers/mplex/lpchannel.nim index ecc2ad88e..4ac246a95 100644 --- a/libp2p/muxers/mplex/lpchannel.nim +++ b/libp2p/muxers/mplex/lpchannel.nim @@ -87,7 +87,7 @@ proc open*(s: LPChannel) {.async: (raises: [CancelledError, LPStreamError]).} = raise exc except LPStreamError as exc: await s.conn.close() - raise exc + raise newException(LPStreamError, "Opening LPChannel failed: " & exc.msg, exc) method closed*(s: LPChannel): bool = s.closedLocal diff --git a/libp2p/muxers/yamux/yamux.nim b/libp2p/muxers/yamux/yamux.nim index 7ab5ca589..5591981ee 100644 --- a/libp2p/muxers/yamux/yamux.nim +++ b/libp2p/muxers/yamux/yamux.nim @@ -587,10 +587,12 @@ method handle*(m: Yamux) {.async: (raises: []).} = let channel = try: m.channels[header.streamId] - except KeyError: + except KeyError as e: raise newException( YamuxError, - "Stream was cleaned up before handling data: " & $header.streamId, + "Stream was cleaned up before handling data: " & $header.streamId & " : " & + e.msg, + e, ) if header.msgType == WindowUpdate: diff --git a/libp2p/nameresolving/dnsresolver.nim b/libp2p/nameresolving/dnsresolver.nim index e9a72f498..08a517c59 100644 --- a/libp2p/nameresolving/dnsresolver.nim +++ b/libp2p/nameresolving/dnsresolver.nim @@ -78,23 +78,23 @@ proc getDnsResponse( try: await receivedDataFuture.wait(5.seconds) #unix default - except AsyncTimeoutError: - raise newException(IOError, "DNS server timeout") + except AsyncTimeoutError as e: + raise newException(IOError, "DNS server timeout: " & e.msg, e) let rawResponse = sock.getMessage() try: parseResponse(string.fromBytes(rawResponse)) except IOError as exc: - raise exc + raise newException(IOError, "Failed to parse DNS response: " & exc.msg, exc) except OSError as exc: - raise exc + raise newException(OSError, "Failed to parse DNS response: " & exc.msg, exc) except ValueError as exc: - raise exc + raise newException(ValueError, "Failed to parse DNS response: " & exc.msg, exc) except Exception as exc: # Nim 1.6: parseResponse can has a raises: [Exception, ..] because of # https://github.com/nim-lang/Nim/commit/035134de429b5d99c5607c5fae912762bebb6008 # it can't actually raise though - raiseAssert exc.msg + raiseAssert "Exception parsing DN response: " & exc.msg finally: await sock.closeWait() diff --git a/libp2p/peerinfo.nim b/libp2p/peerinfo.nim index 6f2960650..ac23fac84 100644 --- a/libp2p/peerinfo.nim +++ b/libp2p/peerinfo.nim @@ -101,8 +101,10 @@ proc new*( let pubkey = try: key.getPublicKey().tryGet() - except CatchableError: - raise newException(PeerInfoError, "invalid private key") + except CatchableError as e: + raise newException( + PeerInfoError, "invalid private key creating PeerInfo: " & e.msg, e + ) let peerId = PeerId.init(key).tryGet() diff --git a/libp2p/protocols/connectivity/autonat/client.nim b/libp2p/protocols/connectivity/autonat/client.nim index 77d404fb1..2dacc7957 100644 --- a/libp2p/protocols/connectivity/autonat/client.nim +++ b/libp2p/protocols/connectivity/autonat/client.nim @@ -87,7 +87,7 @@ method dialMe*( except CancelledError as e: raise e except CatchableError as e: - raise newException(AutonatError, "read Dial response failed", e) + raise newException(AutonatError, "read Dial response failed: " & e.msg, e) let response = getResponseOrRaise(AutonatMsg.decode(respBytes)) diff --git a/libp2p/protocols/connectivity/dcutr/client.nim b/libp2p/protocols/connectivity/dcutr/client.nim index 80ddf2c3c..2849332df 100644 --- a/libp2p/protocols/connectivity/dcutr/client.nim +++ b/libp2p/protocols/connectivity/dcutr/client.nim @@ -107,7 +107,9 @@ proc startSync*( description = err.msg raise newException( DcutrError, - "Unexpected error when Dcutr initiator tried to connect to the remote peer", err, + "Unexpected error when Dcutr initiator tried to connect to the remote peer: " & + err.msg, + err, ) finally: if stream != nil: diff --git a/libp2p/protocols/connectivity/relay/client.nim b/libp2p/protocols/connectivity/relay/client.nim index 95094fbd7..5441df9ef 100644 --- a/libp2p/protocols/connectivity/relay/client.nim +++ b/libp2p/protocols/connectivity/relay/client.nim @@ -148,7 +148,7 @@ proc dialPeerV1*( raise exc except LPStreamError as exc: trace "error writing hop request", description = exc.msg - raise newException(RelayV1DialError, "error writing hop request", exc) + raise newException(RelayV1DialError, "error writing hop request: " & exc.msg, exc) let msgRcvFromRelayOpt = try: @@ -158,7 +158,8 @@ proc dialPeerV1*( except LPStreamError as exc: trace "error reading stop response", description = exc.msg await sendStatus(conn, StatusV1.HopCantOpenDstStream) - raise newException(RelayV1DialError, "error reading stop response", exc) + raise + newException(RelayV1DialError, "error reading stop response: " & exc.msg, exc) try: let msgRcvFromRelay = msgRcvFromRelayOpt.valueOr: @@ -173,10 +174,16 @@ proc dialPeerV1*( ) except RelayV1DialError as exc: await sendStatus(conn, StatusV1.HopCantOpenDstStream) - raise exc + raise newException( + RelayV1DialError, + "Hop can't open destination stream after sendStatus: " & exc.msg, + exc, + ) except ValueError as exc: await sendStatus(conn, StatusV1.HopCantOpenDstStream) - raise newException(RelayV1DialError, exc.msg) + raise newException( + RelayV1DialError, "Exception reading msg in dialPeerV1: " & exc.msg, exc + ) result = conn proc dialPeerV2*( @@ -199,7 +206,8 @@ proc dialPeerV2*( raise exc except CatchableError as exc: trace "error reading stop response", description = exc.msg - raise newException(RelayV2DialError, exc.msg) + raise + newException(RelayV2DialError, "Exception decoding HopMessage: " & exc.msg, exc) if msgRcvFromRelay.msgType != HopMessageType.Status: raise newException(RelayV2DialError, "Unexpected stop response") diff --git a/libp2p/protocols/connectivity/relay/rtransport.nim b/libp2p/protocols/connectivity/relay/rtransport.nim index e7a030232..9072838a9 100644 --- a/libp2p/protocols/connectivity/relay/rtransport.nim +++ b/libp2p/protocols/connectivity/relay/rtransport.nim @@ -76,7 +76,7 @@ proc dial*( if not dstPeerId.init(($(sma[^1].tryGet())).split('/')[2]): raise newException(RelayDialError, "Destination doesn't exist") except RelayDialError as e: - raise e + raise newException(RelayDialError, "dial address not valid: " & e.msg, e) except CatchableError: raise newException(RelayDialError, "dial address not valid") @@ -100,13 +100,13 @@ proc dial*( raise e except DialFailedError as e: safeClose(rc) - raise newException(RelayDialError, "dial relay peer failed", e) + raise newException(RelayDialError, "dial relay peer failed: " & e.msg, e) except RelayV1DialError as e: safeClose(rc) - raise e + raise newException(RelayV1DialError, "dial relay v1 failed: " & e.msg, e) except RelayV2DialError as e: safeClose(rc) - raise e + raise newException(RelayV2DialError, "dial relay v2 failed: " & e.msg, e) method dial*( self: RelayTransport, @@ -121,7 +121,8 @@ method dial*( except CancelledError as e: raise e except CatchableError as e: - raise newException(transport.TransportDialError, e.msg, e) + raise + newException(transport.TransportDialError, "Caught error in dial: " & e.msg, e) method handles*(self: RelayTransport, ma: MultiAddress): bool {.gcsafe.} = try: diff --git a/libp2p/protocols/connectivity/relay/utils.nim b/libp2p/protocols/connectivity/relay/utils.nim index d554a2f02..7e9fbaac1 100644 --- a/libp2p/protocols/connectivity/relay/utils.nim +++ b/libp2p/protocols/connectivity/relay/utils.nim @@ -69,8 +69,8 @@ proc bridge*( while not connSrc.closed() and not connDst.closed(): try: # https://github.com/status-im/nim-chronos/issues/516 discard await race(futSrc, futDst) - except ValueError: - raiseAssert("Futures list is not empty") + except ValueError as e: + raiseAssert("Futures list is not empty: " & e.msg) if futSrc.finished(): bufRead = await futSrc if bufRead > 0: diff --git a/libp2p/protocols/pubsub/floodsub.nim b/libp2p/protocols/pubsub/floodsub.nim index ffe577392..cf3e25cc0 100644 --- a/libp2p/protocols/pubsub/floodsub.nim +++ b/libp2p/protocols/pubsub/floodsub.nim @@ -185,7 +185,7 @@ method init*(f: FloodSub) = try: await f.handleConn(conn, proto) except CancelledError as exc: - trace "Unexpected cancellation in floodsub handler", conn + trace "Unexpected cancellation in floodsub handler", conn, description = exc.msg raise exc f.handler = handler diff --git a/libp2p/protocols/pubsub/gossipsub.nim b/libp2p/protocols/pubsub/gossipsub.nim index bd82950d7..416a536a3 100644 --- a/libp2p/protocols/pubsub/gossipsub.nim +++ b/libp2p/protocols/pubsub/gossipsub.nim @@ -218,7 +218,7 @@ method init*(g: GossipSub) = try: await g.handleConn(conn, proto) except CancelledError as exc: - trace "Unexpected cancellation in gossipsub handler", conn + trace "Unexpected cancellation in gossipsub handler", conn, description = exc.msg raise exc g.handler = handler diff --git a/libp2p/protocols/pubsub/gossipsub/behavior.nim b/libp2p/protocols/pubsub/gossipsub/behavior.nim index dd0caa9c1..5003a37d0 100644 --- a/libp2p/protocols/pubsub/gossipsub/behavior.nim +++ b/libp2p/protocols/pubsub/gossipsub/behavior.nim @@ -457,8 +457,8 @@ proc rebalanceMesh*(g: GossipSub, topic: string, metrics: ptr MeshMetrics = nil) prunes = toSeq( try: g.mesh[topic] - except KeyError: - raiseAssert "have peers" + except KeyError as e: + raiseAssert "have peers: " & e.msg ) # avoid pruning peers we are currently grafting in this heartbeat prunes.keepIf do(x: PubSubPeer) -> bool: @@ -513,8 +513,8 @@ proc rebalanceMesh*(g: GossipSub, topic: string, metrics: ptr MeshMetrics = nil) var peers = toSeq( try: g.mesh[topic] - except KeyError: - raiseAssert "have peers" + except KeyError as e: + raiseAssert "have peers: " & e.msg ) # grafting so high score has priority peers.sort(byScore, SortOrder.Descending) diff --git a/libp2p/protocols/pubsub/pubsubpeer.nim b/libp2p/protocols/pubsub/pubsubpeer.nim index 56fb9dffa..14d533036 100644 --- a/libp2p/protocols/pubsub/pubsubpeer.nim +++ b/libp2p/protocols/pubsub/pubsubpeer.nim @@ -230,10 +230,10 @@ proc handle*(p: PubSubPeer, conn: Connection) {.async: (raises: []).} = conn, peer = p, closed = conn.closed, description = exc.msg finally: await conn.close() - except CancelledError: + except CancelledError as e: # This is top-level procedure which will work as separate task, so it # do not need to propagate CancelledError. - trace "Unexpected cancellation in PubSubPeer.handle" + trace "Unexpected cancellation in PubSubPeer.handle", description = e.msg finally: debug "exiting pubsub read loop", conn, peer = p, closed = conn.closed @@ -266,7 +266,7 @@ proc connectOnce( await p.getConn().wait(5.seconds) except AsyncTimeoutError as error: trace "getConn timed out", description = error.msg - raise (ref LPError)(msg: "Cannot establish send connection") + raise (ref LPError)(msg: "Cannot establish send connection: " & error.msg) # When the send channel goes up, subscriptions need to be sent to the # remote peer - if we had multiple channels up and one goes down, all diff --git a/libp2p/protocols/rendezvous.nim b/libp2p/protocols/rendezvous.nim index 03bdfaf42..2682fa368 100644 --- a/libp2p/protocols/rendezvous.nim +++ b/libp2p/protocols/rendezvous.nim @@ -419,8 +419,8 @@ proc save( ) rdv.namespaces[nsSalted].add(rdv.registered.high) # rdv.registerEvent.fire() - except KeyError: - doAssert false, "Should have key" + except KeyError as e: + doAssert false, "Should have key: " & e.msg proc register(rdv: RendezVous, conn: Connection, r: Register): Future[void] = trace "Received Register", peerId = conn.peerId, ns = r.ns diff --git a/libp2p/protocols/secure/secure.nim b/libp2p/protocols/secure/secure.nim index a182f1fbd..06d563fba 100644 --- a/libp2p/protocols/secure/secure.nim +++ b/libp2p/protocols/secure/secure.nim @@ -110,8 +110,8 @@ proc handleConn( fut2 = sconn.join() try: # https://github.com/status-im/nim-chronos/issues/516 discard await race(fut1, fut2) - except ValueError: - raiseAssert("Futures list is not empty") + except ValueError as e: + raiseAssert("Futures list is not empty: " & e.msg) # at least one join() completed, cancel pending one, if any if not fut1.finished: await fut1.cancelAndWait() @@ -182,14 +182,14 @@ method readOnce*( except LPStreamEOFError as err: s.isEof = true await s.close() - raise err + raise newException(LPStreamEOFError, "Secure connection EOF: " & err.msg, err) except CancelledError as exc: raise exc except LPStreamError as err: debug "Error while reading message from secure connection, closing.", error = err.name, message = err.msg, connection = s await s.close() - raise err + raise newException(LPStreamError, "Secure connection read error: " & err.msg, err) var p = cast[ptr UncheckedArray[byte]](pbytes) return s.buf.consumeTo(toOpenArray(p, 0, nbytes - 1)) diff --git a/libp2p/services/hpservice.nim b/libp2p/services/hpservice.nim index 26fdc4d39..325671c62 100644 --- a/libp2p/services/hpservice.nim +++ b/libp2p/services/hpservice.nim @@ -55,7 +55,7 @@ proc tryStartingDirectConn( if not isRelayed.get(false) and address.isPublicMA(): return await tryConnect(address) except CatchableError as err: - debug "Failed to create direct connection.", err = err.msg + debug "Failed to create direct connection.", description = err.msg continue return false @@ -91,7 +91,7 @@ proc newConnectedPeerHandler( except CancelledError as err: raise err except CatchableError as err: - debug "Hole punching failed during dcutr", err = err.msg + debug "Hole punching failed during dcutr", description = err.msg method setup*( self: HPService, switch: Switch @@ -104,7 +104,7 @@ method setup*( let dcutrProto = Dcutr.new(switch) switch.mount(dcutrProto) except LPError as err: - error "Failed to mount Dcutr", err = err.msg + error "Failed to mount Dcutr", description = err.msg self.newConnectedPeerHandler = proc( peerId: PeerId, event: PeerEvent diff --git a/libp2p/stream/bufferstream.nim b/libp2p/stream/bufferstream.nim index 93dd1a8fc..0844da218 100644 --- a/libp2p/stream/bufferstream.nim +++ b/libp2p/stream/bufferstream.nim @@ -199,8 +199,10 @@ method closeImpl*(s: BufferStream): Future[void] {.async: (raises: [], raw: true elif s.pushing: if not s.readQueue.empty(): discard s.readQueue.popFirstNoWait() - except AsyncQueueFullError, AsyncQueueEmptyError: - raiseAssert(getCurrentExceptionMsg()) + except AsyncQueueFullError as e: + raiseAssert("closeImpl failed queue full: " & e.msg) + except AsyncQueueEmptyError as e: + raiseAssert("closeImpl failed queue empty: " & e.msg) trace "Closed BufferStream", s diff --git a/libp2p/stream/lpstream.nim b/libp2p/stream/lpstream.nim index 8c0daf9be..23c162d2e 100644 --- a/libp2p/stream/lpstream.nim +++ b/libp2p/stream/lpstream.nim @@ -328,7 +328,7 @@ proc closeWithEOF*(s: LPStream): Future[void] {.async: (raises: []), public.} = debug "Unexpected bytes while waiting for EOF", s except CancelledError: discard - except LPStreamEOFError: - trace "Expected EOF came", s + except LPStreamEOFError as e: + trace "Expected EOF came", s, description = e.msg except LPStreamError as exc: debug "Unexpected error while waiting for EOF", s, description = exc.msg diff --git a/libp2p/switch.nim b/libp2p/switch.nim index e982989d3..91ee52b91 100644 --- a/libp2p/switch.nim +++ b/libp2p/switch.nim @@ -233,7 +233,7 @@ proc upgrader( except CancelledError as e: raise e except CatchableError as e: - raise newException(UpgradeError, e.msg, e) + raise newException(UpgradeError, "catchable error upgrader: " & e.msg, e) proc upgradeMonitor( switch: Switch, trans: Transport, conn: Connection, upgrades: AsyncSemaphore @@ -275,7 +275,8 @@ proc accept(s: Switch, transport: Transport) {.async: (raises: []).} = await transport.accept() except CatchableError as exc: slot.release() - raise exc + raise + newException(CatchableError, "failed to accept connection: " & exc.msg, exc) slot.trackConnection(conn) if isNil(conn): # A nil connection means that we might have hit a diff --git a/libp2p/transports/quictransport.nim b/libp2p/transports/quictransport.nim index 4846bf338..9161c9dde 100644 --- a/libp2p/transports/quictransport.nim +++ b/libp2p/transports/quictransport.nim @@ -101,7 +101,7 @@ proc getStream*( return QuicStream.new(stream, session.observedAddr, session.peerId) except CatchableError as exc: # TODO: incomingStream is using {.async.} with no raises - raise (ref QuicTransportError)(msg: exc.msg, parent: exc) + raise (ref QuicTransportError)(msg: "error in getStream: " & exc.msg, parent: exc) method getWrapped*(self: QuicSession): P2PConnection = nil @@ -119,7 +119,7 @@ method newStream*( try: return await m.quicSession.getStream(Direction.Out) except CatchableError as exc: - raise newException(MuxerError, exc.msg, exc) + raise newException(MuxerError, "error in newStream: " & exc.msg, exc) proc handleStream(m: QuicMuxer, chann: QuicStream) {.async: (raises: []).} = ## call the muxer stream handler for this channel @@ -236,11 +236,16 @@ method start*( except QuicConfigError as exc: doAssert false, "invalid quic setup: " & $exc.msg except TLSCertificateError as exc: - raise (ref QuicTransportError)(msg: exc.msg, parent: exc) + raise (ref QuicTransportError)( + msg: "tlscert error in quic start: " & exc.msg, parent: exc + ) except QuicError as exc: - raise (ref QuicTransportError)(msg: exc.msg, parent: exc) + raise + (ref QuicTransportError)(msg: "quicerror in quic start: " & exc.msg, parent: exc) except TransportOsError as exc: - raise (ref QuicTransportError)(msg: exc.msg, parent: exc) + raise (ref QuicTransportError)( + msg: "transport error in quic start: " & exc.msg, parent: exc + ) self.running = true method stop*(transport: QuicTransport) {.async: (raises: []).} = @@ -318,7 +323,7 @@ method dial*( except CancelledError as e: raise e except CatchableError as e: - raise newException(QuicTransportDialError, e.msg, e) + raise newException(QuicTransportDialError, "error in quic dial:" & e.msg, e) method upgrade*( self: QuicTransport, conn: P2PConnection, peerId: Opt[PeerId] diff --git a/libp2p/transports/tcptransport.nim b/libp2p/transports/tcptransport.nim index 22890ce38..ddcb16a0f 100644 --- a/libp2p/transports/tcptransport.nim +++ b/libp2p/transports/tcptransport.nim @@ -133,7 +133,9 @@ method start*( try: createStreamServer(ta, flags = self.flags) except common.TransportError as exc: - raise (ref TcpTransportError)(msg: exc.msg, parent: exc) + raise (ref TcpTransportError)( + msg: "transport error in TcpTransport start:" & exc.msg, parent: exc + ) self.servers &= server @@ -250,9 +252,13 @@ method accept*( except TransportUseClosedError as exc: raise newTransportClosedError(exc) except TransportOsError as exc: - raise (ref TcpTransportError)(msg: exc.msg, parent: exc) + raise (ref TcpTransportError)( + msg: "TransportOs error in accept:" & exc.msg, parent: exc + ) except common.TransportError as exc: # Needed for chronos 4.0.0 support - raise (ref TcpTransportError)(msg: exc.msg, parent: exc) + raise (ref TcpTransportError)( + msg: "TransportError in accept: " & exc.msg, parent: exc + ) except CancelledError as exc: cancelAcceptFuts() raise exc @@ -302,7 +308,8 @@ method dial*( except CancelledError as exc: raise exc except CatchableError as exc: - raise (ref TcpTransportError)(msg: exc.msg, parent: exc) + raise + (ref TcpTransportError)(msg: "TcpTransport dial error: " & exc.msg, parent: exc) # If `stop` is called after `connect` but before `await` returns, we might # end up with a race condition where `stop` returns but not all connections @@ -318,7 +325,7 @@ method dial*( MultiAddress.init(transp.remoteAddress).expect("remote address is valid") except TransportOsError as exc: safeCloseWait(transp) - raise (ref TcpTransportError)(msg: exc.msg) + raise (ref TcpTransportError)(msg: "MultiAddress.init error in dial: " & exc.msg) self.connHandler(transp, Opt.some(observedAddr), Direction.Out) diff --git a/libp2p/transports/tls/certificate.nim b/libp2p/transports/tls/certificate.nim index 9494b2013..28125557e 100644 --- a/libp2p/transports/tls/certificate.nim +++ b/libp2p/transports/tls/certificate.nim @@ -118,8 +118,8 @@ proc makeASN1Time(time: Time): string {.inline.} = try: let f = initTimeFormat("yyyyMMddhhmmss") format(time.utc(), f) - except TimeFormatParseError: - raiseAssert "time format is const and checked with test" + except TimeFormatParseError as e: + raiseAssert "time format is const and checked with test: " & e.msg return str & "Z" @@ -278,7 +278,7 @@ proc parse*( validTo = parseCertTime($certParsed.valid_to) except TimeParseError as e: raise newException( - CertificateParsingError, "Failed to parse certificate validity time, " & $e.msg + CertificateParsingError, "Failed to parse certificate validity time: " & $e.msg, e ) P2pCertificate( diff --git a/libp2p/transports/tortransport.nim b/libp2p/transports/tortransport.nim index 3f0b73d43..cd06a3996 100644 --- a/libp2p/transports/tortransport.nim +++ b/libp2p/transports/tortransport.nim @@ -243,7 +243,9 @@ method dial*( raise e except CatchableError as e: safeCloseWait(transp) - raise newException(transport.TransportDialError, e.msg, e) + raise newException( + transport.TransportDialError, "error in dial TorTransport: " & e.msg, e + ) method start*( self: TorTransport, addrs: seq[MultiAddress] diff --git a/libp2p/transports/wstransport.nim b/libp2p/transports/wstransport.nim index 5416c92a9..2a1dfe22f 100644 --- a/libp2p/transports/wstransport.nim +++ b/libp2p/transports/wstransport.nim @@ -160,7 +160,9 @@ method start*( else: HttpServer.create(address, handshakeTimeout = self.handshakeTimeout) except CatchableError as exc: - raise (ref WsTransportError)(msg: exc.msg, parent: exc) + raise (ref WsTransportError)( + msg: "error in WsTransport start: " & exc.msg, parent: exc + ) self.httpservers &= httpserver @@ -309,7 +311,9 @@ method accept*( debug "OS Error", description = exc.msg except CatchableError as exc: info "Unexpected error accepting connection", description = exc.msg - raise newException(transport.TransportError, exc.msg, exc) + raise newException( + transport.TransportError, "Error in WsTransport accept: " & exc.msg, exc + ) method dial*( self: WsTransport, @@ -338,7 +342,9 @@ method dial*( raise e except CatchableError as e: safeClose(transp) - raise newException(transport.TransportDialError, e.msg, e) + raise newException( + transport.TransportDialError, "error in WsTransport dial: " & e.msg, e + ) method handles*(t: WsTransport, address: MultiAddress): bool {.gcsafe, raises: [].} = if procCall Transport(t).handles(address): diff --git a/libp2p/utility.nim b/libp2p/utility.nim index bde2d2bcb..12a8ef9b0 100644 --- a/libp2p/utility.nim +++ b/libp2p/utility.nim @@ -54,8 +54,9 @@ when defined(libp2p_agents_metrics): proc safeToLowerAscii*(s: string): Result[string, cstring] = try: ok(s.toLowerAscii()) - except CatchableError: - err("toLowerAscii failed") + except CatchableError as e: + let errMsg = "toLowerAscii failed: " & e.msg + err(errMsg.cstring) const KnownLibP2PAgents* {.strdefine.} = "nim-libp2p" diff --git a/libp2p/utils/future.nim b/libp2p/utils/future.nim index 87831cd00..b25fb8eec 100644 --- a/libp2p/utils/future.nim +++ b/libp2p/utils/future.nim @@ -27,9 +27,9 @@ proc anyCompleted*[T]( if raceFut.completed: return raceFut requests.del(requests.find(raceFut)) - except ValueError: + except ValueError as e: raise newException( - AllFuturesFailedError, "None of the futures completed successfully" + AllFuturesFailedError, "None of the futures completed successfully: " & e.msg, e ) except CancelledError as exc: raise exc diff --git a/libp2p/wire.nim b/libp2p/wire.nim index cab5b24b6..7f3a4f963 100644 --- a/libp2p/wire.nim +++ b/libp2p/wire.nim @@ -108,7 +108,9 @@ proc createStreamServer*[T]( ): StreamServer {.raises: [LPError, MaInvalidAddress].} = ## Create new TCP stream server which bounds to ``ma`` address. if not (RTRANSPMA.match(ma)): - raise newException(MaInvalidAddress, "Incorrect or unsupported address!") + raise newException( + MaInvalidAddress, "Incorrect or unsupported address in createStreamServer" + ) try: return createStreamServer( @@ -123,7 +125,7 @@ proc createStreamServer*[T]( init, ) except CatchableError as exc: - raise newException(LPError, exc.msg) + raise newException(LPError, "failed createStreamServer: " & exc.msg, exc) proc createStreamServer*[T]( ma: MultiAddress, @@ -146,7 +148,7 @@ proc createStreamServer*[T]( initTAddress(ma).tryGet(), flags, udata, sock, backlog, bufferSize, child, init ) except CatchableError as exc: - raise newException(LPError, exc.msg) + raise newException(LPError, "failed simpler createStreamServer: " & exc.msg, exc) proc createAsyncSocket*(ma: MultiAddress): AsyncFD {.raises: [ValueError, LPError].} = ## Create new asynchronous socket using MultiAddress' ``ma`` socket type and @@ -178,7 +180,9 @@ proc createAsyncSocket*(ma: MultiAddress): AsyncFD {.raises: [ValueError, LPErro try: createAsyncSocket(address.getDomain(), socktype, protocol) except CatchableError as exc: - raise newException(LPError, exc.msg) + raise newException( + LPError, "Convert exception to LPError in createAsyncSocket: " & exc.msg, exc + ) proc bindAsyncSocket*(sock: AsyncFD, ma: MultiAddress): bool {.raises: [LPError].} = ## Bind socket ``sock`` to MultiAddress ``ma``. diff --git a/tools/pbcap_parser.nim b/tools/pbcap_parser.nim index 5b9803202..f27f103c8 100644 --- a/tools/pbcap_parser.nim +++ b/tools/pbcap_parser.nim @@ -87,5 +87,5 @@ when isMainModule: let dump = if cmd == "dump": true else: false try: echo parseFile(paramStr(2), dump) - except: - fatal "Could not read pbcap file", filename = path + except CatchableError as e: + fatal "Could not read pbcap file", description = e.msg, filename = path