fix: fixed multiple bare except warnings

This commit is contained in:
Lorenzo Delgado 2023-04-04 15:34:53 +02:00 committed by GitHub
parent 7c229ece3b
commit caf78249b2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
15 changed files with 140 additions and 140 deletions

View File

@ -339,7 +339,7 @@ when isMainModule:
# Adhere to NO_COLOR initiative: https://no-color.org/ # Adhere to NO_COLOR initiative: https://no-color.org/
let color = try: not parseBool(os.getEnv("NO_COLOR", "false")) let color = try: not parseBool(os.getEnv("NO_COLOR", "false"))
except: true except CatchableError: true
logging.setupLogLevel(conf.logLevel) logging.setupLogLevel(conf.logLevel)
logging.setupLogFormat(conf.logFormat, color) logging.setupLogFormat(conf.logFormat, color)

View File

@ -451,7 +451,7 @@ proc parseCmdArg*(T: type crypto.PrivateKey, p: string): T =
try: try:
let key = SkPrivateKey.init(utils.fromHex(p)).tryGet() let key = SkPrivateKey.init(utils.fromHex(p)).tryGet()
crypto.PrivateKey(scheme: Secp256k1, skkey: key) crypto.PrivateKey(scheme: Secp256k1, skkey: key)
except: except CatchableError:
raise newException(ConfigurationError, "Invalid private key") raise newException(ConfigurationError, "Invalid private key")
proc completeCmdArg*(T: type crypto.PrivateKey, val: string): seq[string] = proc completeCmdArg*(T: type crypto.PrivateKey, val: string): seq[string] =
@ -461,7 +461,7 @@ proc completeCmdArg*(T: type crypto.PrivateKey, val: string): seq[string] =
proc parseCmdArg*(T: type ValidIpAddress, p: string): T = proc parseCmdArg*(T: type ValidIpAddress, p: string): T =
try: try:
ValidIpAddress.init(p) ValidIpAddress.init(p)
except: except CatchableError:
raise newException(ConfigurationError, "Invalid IP address") raise newException(ConfigurationError, "Invalid IP address")
proc completeCmdArg*(T: type ValidIpAddress, val: string): seq[string] = proc completeCmdArg*(T: type ValidIpAddress, val: string): seq[string] =
@ -476,7 +476,7 @@ proc defaultListenAddress*(): ValidIpAddress =
proc parseCmdArg*(T: type Port, p: string): T = proc parseCmdArg*(T: type Port, p: string): T =
try: try:
Port(parseInt(p)) Port(parseInt(p))
except: except CatchableError:
raise newException(ConfigurationError, "Invalid Port number") raise newException(ConfigurationError, "Invalid Port number")
proc completeCmdArg*(T: type Port, val: string): seq[string] = proc completeCmdArg*(T: type Port, val: string): seq[string] =
@ -485,7 +485,7 @@ proc completeCmdArg*(T: type Port, val: string): seq[string] =
proc parseCmdArg*(T: type Option[int], p: string): T = proc parseCmdArg*(T: type Option[int], p: string): T =
try: try:
some(parseInt(p)) some(parseInt(p))
except: except CatchableError:
raise newException(ConfigurationError, "Invalid number") raise newException(ConfigurationError, "Invalid number")
## Configuration validation ## Configuration validation

View File

@ -608,7 +608,7 @@ when isMainModule:
# Adhere to NO_COLOR initiative: https://no-color.org/ # Adhere to NO_COLOR initiative: https://no-color.org/
let color = try: not parseBool(os.getEnv("NO_COLOR", "false")) let color = try: not parseBool(os.getEnv("NO_COLOR", "false"))
except: true except CatchableError: true
logging.setupLogLevel(conf.logLevel) logging.setupLogLevel(conf.logLevel)
logging.setupLogFormat(conf.logFormat, color) logging.setupLogFormat(conf.logFormat, color)

View File

@ -133,11 +133,11 @@ proc runGanache(): Process =
ganacheStartLog.add(cmdline) ganacheStartLog.add(cmdline)
if cmdline.contains("Listening on 127.0.0.1:8540"): if cmdline.contains("Listening on 127.0.0.1:8540"):
break break
except: except CatchableError:
break break
debug "Ganache daemon is running and ready", pid=ganachePID, startLog=ganacheStartLog debug "Ganache daemon is running and ready", pid=ganachePID, startLog=ganacheStartLog
return runGanache return runGanache
except: except: # TODO: Fix "BareExcept" warning
error "Ganache daemon run failed" error "Ganache daemon run failed"
@ -153,7 +153,7 @@ proc stopGanache(runGanache: Process) {.used.} =
# ref: https://nim-lang.org/docs/osproc.html#waitForExit%2CProcess%2Cint # ref: https://nim-lang.org/docs/osproc.html#waitForExit%2CProcess%2Cint
# debug "ganache logs", logs=runGanache.outputstream.readAll() # debug "ganache logs", logs=runGanache.outputstream.readAll()
debug "Sent SIGTERM to Ganache", ganachePID=ganachePID debug "Sent SIGTERM to Ganache", ganachePID=ganachePID
except: except CatchableError:
error "Ganache daemon termination failed: ", err = getCurrentExceptionMsg() error "Ganache daemon termination failed: ", err = getCurrentExceptionMsg()
proc setup(signer = true): Future[OnchainGroupManager] {.async.} = proc setup(signer = true): Future[OnchainGroupManager] {.async.} =

View File

@ -151,7 +151,7 @@ proc populateInfoFromIp(allPeersRef: CustomPeersTableRef,
await sleepAsync(1400) await sleepAsync(1400)
let response = await restClient.ipToLocation(allPeersRef[peer].ip) let response = await restClient.ipToLocation(allPeersRef[peer].ip)
location = response.data location = response.data
except: except CatchableError:
warn "could not get location", ip=allPeersRef[peer].ip warn "could not get location", ip=allPeersRef[peer].ip
continue continue
allPeersRef[peer].country = location.country allPeersRef[peer].country = location.country
@ -214,7 +214,7 @@ proc getBootstrapFromDiscDns(conf: NetworkMonitorConf): Result[seq[enr.Record],
if tenrRes.isOk() and (tenrRes.get().udp.isSome() or tenrRes.get().udp6.isSome()): if tenrRes.isOk() and (tenrRes.get().udp.isSome() or tenrRes.get().udp6.isSome()):
discv5BootstrapEnrs.add(enr) discv5BootstrapEnrs.add(enr)
return ok(discv5BootstrapEnrs) return ok(discv5BootstrapEnrs)
except: except CatchableError:
error("failed discovering peers from DNS") error("failed discovering peers from DNS")
proc initAndStartNode(conf: NetworkMonitorConf): Result[WakuNode, string] = proc initAndStartNode(conf: NetworkMonitorConf): Result[WakuNode, string] =
@ -249,7 +249,7 @@ proc initAndStartNode(conf: NetworkMonitorConf): Result[WakuNode, string] =
node.wakuDiscv5.protocol.open() node.wakuDiscv5.protocol.open()
return ok(node) return ok(node)
except: except CatchableError:
error("could not start node") error("could not start node")
proc startRestApiServer(conf: NetworkMonitorConf, proc startRestApiServer(conf: NetworkMonitorConf,
@ -266,7 +266,7 @@ proc startRestApiServer(conf: NetworkMonitorConf,
var sres = RestServerRef.new(router, serverAddress) var sres = RestServerRef.new(router, serverAddress)
let restServer = sres.get() let restServer = sres.get()
restServer.start() restServer.start()
except: except CatchableError:
error("could not start rest api server") error("could not start rest api server")
ok() ok()

View File

@ -44,7 +44,7 @@ proc decodeBytes*(t: typedesc[NodeLocation], value: openArray[byte],
long: $jsonContent["lon"].getFloat(), long: $jsonContent["lon"].getFloat(),
isp: jsonContent["isp"].getStr() isp: jsonContent["isp"].getStr()
)) ))
except: except CatchableError:
return err("failed to get the location: " & getCurrentExceptionMsg()) return err("failed to get the location: " & getCurrentExceptionMsg())
proc encodeString*(value: string): RestResult[string] = proc encodeString*(value: string): RestResult[string] =

View File

@ -24,7 +24,7 @@ converter toChroniclesLogLevel(level: LogLevel): chronicles.LogLevel =
## Map logging log levels to the corresponding nim-chronicles' log level ## Map logging log levels to the corresponding nim-chronicles' log level
try: try:
parseEnum[chronicles.LogLevel]($level) parseEnum[chronicles.LogLevel]($level)
except: except CatchableError:
chronicles.LogLevel.NONE chronicles.LogLevel.NONE
@ -71,7 +71,7 @@ proc writeAndFlush(f: File, s: LogOutputStr) =
try: try:
f.write(s) f.write(s)
f.flushFile() f.flushFile()
except: except CatchableError:
logLoggingFailure(cstring(s), getCurrentException()) logLoggingFailure(cstring(s), getCurrentException())

View File

@ -88,7 +88,7 @@ proc readValue*(reader: var JsonReader[RestJson], value: var RelayWakuMessage)
# Check for reapeated keys # Check for reapeated keys
if keys.containsOrIncl(fieldName): if keys.containsOrIncl(fieldName):
let err = try: fmt"Multiple `{fieldName}` fields found" let err = try: fmt"Multiple `{fieldName}` fields found"
except: "Multiple fields with the same name found" except CatchableError: "Multiple fields with the same name found"
reader.raiseUnexpectedField(err, "RelayWakuMessage") reader.raiseUnexpectedField(err, "RelayWakuMessage")
case fieldName case fieldName

View File

@ -255,7 +255,7 @@ method getMessages*(
): ArchiveDriverResult[seq[ArchiveRow]] = ): ArchiveDriverResult[seq[ArchiveRow]] =
let cursor = cursor.map(toIndex) let cursor = cursor.map(toIndex)
let matchesQuery: QueryFilterMatcher = proc(row: IndexedWakuMessage): bool = let matchesQuery: QueryFilterMatcher = func(row: IndexedWakuMessage): bool =
if pubsubTopic.isSome() and row.pubsubTopic != pubsubTopic.get(): if pubsubTopic.isSome() and row.pubsubTopic != pubsubTopic.get():
return false return false
@ -273,7 +273,7 @@ method getMessages*(
var pageRes: QueueDriverGetPageResult var pageRes: QueueDriverGetPageResult
try: try:
pageRes = driver.getPage(maxPageSize, ascendingOrder, cursor, matchesQuery) pageRes = driver.getPage(maxPageSize, ascendingOrder, cursor, matchesQuery)
except: except: # TODO: Fix "BareExcept" warning
return err(getCurrentExceptionMsg()) return err(getCurrentExceptionMsg())
if pageRes.isErr(): if pageRes.isErr():

View File

@ -47,7 +47,7 @@ proc clear(m: var SubscriptionManager) =
proc registerSubscription(m: SubscriptionManager, pubsubTopic: PubsubTopic, contentTopic: ContentTopic, handler: FilterPushHandler) = proc registerSubscription(m: SubscriptionManager, pubsubTopic: PubsubTopic, contentTopic: ContentTopic, handler: FilterPushHandler) =
try: try:
m.subscriptions[(pubsubTopic, contentTopic)]= handler m.subscriptions[(pubsubTopic, contentTopic)]= handler
except: except: # TODO: Fix "BareExcept" warning
error "failed to register filter subscription", error=getCurrentExceptionMsg() error "failed to register filter subscription", error=getCurrentExceptionMsg()
proc removeSubscription(m: SubscriptionManager, pubsubTopic: PubsubTopic, contentTopic: ContentTopic) = proc removeSubscription(m: SubscriptionManager, pubsubTopic: PubsubTopic, contentTopic: ContentTopic) =
@ -60,7 +60,7 @@ proc notifySubscriptionHandler(m: SubscriptionManager, pubsubTopic: PubsubTopic,
try: try:
let handler = m.subscriptions[(pubsubTopic, contentTopic)] let handler = m.subscriptions[(pubsubTopic, contentTopic)]
handler(pubsubTopic, message) handler(pubsubTopic, message)
except: except: # TODO: Fix "BareExcept" warning
discard discard
proc getSubscriptionsCount(m: SubscriptionManager): int = proc getSubscriptionsCount(m: SubscriptionManager): int =

View File

@ -183,7 +183,7 @@ proc addMembershipCredentials*(path: string,
# We add it to the credentials field of the keystore # We add it to the credentials field of the keystore
jsonKeystore["credentials"].add(keyfileRes.get()) jsonKeystore["credentials"].add(keyfileRes.get())
except: except CatchableError:
return err(KeystoreJsonError) return err(KeystoreJsonError)
# We save to disk the (updated) keystore. # We save to disk the (updated) keystore.
@ -235,7 +235,7 @@ proc getMembershipCredentials*(path: string,
if filteredCredentialOpt.isSome(): if filteredCredentialOpt.isSome():
outputMembershipCredentials.add(filteredCredentialOpt.get()) outputMembershipCredentials.add(filteredCredentialOpt.get())
except: except CatchableError:
return err(KeystoreJsonError) return err(KeystoreJsonError)
return ok(outputMembershipCredentials) return ok(outputMembershipCredentials)

View File

@ -25,7 +25,7 @@ proc save*(json: JsonNode, path: string, separator: string): KeystoreResult[void
if fileExists(path): if fileExists(path):
try: try:
moveFile(path, path & ".bkp") moveFile(path, path & ".bkp")
except: except: # TODO: Fix "BareExcept" warning
return err(KeystoreOsError) return err(KeystoreOsError)
# We save the updated json # We save the updated json
@ -45,7 +45,7 @@ proc save*(json: JsonNode, path: string, separator: string): KeystoreResult[void
f.close() f.close()
removeFile(path) removeFile(path)
moveFile(path & ".bkp", path) moveFile(path & ".bkp", path)
except: except: # TODO: Fix "BareExcept" warning
# Unlucky, we just fail # Unlucky, we just fail
return err(KeystoreOsError) return err(KeystoreOsError)
return err(KeystoreOsError) return err(KeystoreOsError)
@ -56,7 +56,7 @@ proc save*(json: JsonNode, path: string, separator: string): KeystoreResult[void
if fileExists(path & ".bkp"): if fileExists(path & ".bkp"):
try: try:
removeFile(path & ".bkp") removeFile(path & ".bkp")
except: except CatchableError:
return err(KeystoreOsError) return err(KeystoreOsError)
return ok() return ok()

View File

@ -487,7 +487,7 @@ proc stepHandshake*(rng: var rand.HmacDrbgContext, hs: var HandshakeState, readP
# We initialize a payload v2 and we set proper protocol ID (if supported) # We initialize a payload v2 and we set proper protocol ID (if supported)
try: try:
hsStepResult.payload2.protocolId = PayloadV2ProtocolIDs[hs.handshakePattern.name] hsStepResult.payload2.protocolId = PayloadV2ProtocolIDs[hs.handshakePattern.name]
except: except CatchableError:
raise newException(NoiseMalformedHandshake, "Handshake Pattern not supported") raise newException(NoiseMalformedHandshake, "Handshake Pattern not supported")
# We set the messageNametag and the handshake and transport messages # We set the messageNametag and the handshake and transport messages

View File

@ -189,7 +189,7 @@ proc print*(self: HandshakePattern)
stdout.write ", ", token stdout.write ", ", token
stdout.write "\n" stdout.write "\n"
stdout.flushFile() stdout.flushFile()
except: except CatchableError:
raise newException(NoiseMalformedHandshake, "HandshakePattern malformed") raise newException(NoiseMalformedHandshake, "HandshakePattern malformed")
# Hashes a Noise protocol name using SHA256 # Hashes a Noise protocol name using SHA256

View File

@ -175,7 +175,7 @@ proc parseEvent*(event: type MemberRegistered,
# Parse the index # Parse the index
offset += decode(data, offset, index) offset += decode(data, offset, index)
return ok(Membership(idCommitment: idComm.toIDCommitment(), index: index.toMembershipIndex())) return ok(Membership(idCommitment: idComm.toIDCommitment(), index: index.toMembershipIndex()))
except: except CatchableError:
return err("failed to parse the data field of the MemberRegistered event") return err("failed to parse the data field of the MemberRegistered event")
type BlockTable* = OrderedTable[BlockNumber, seq[Membership]] type BlockTable* = OrderedTable[BlockNumber, seq[Membership]]
@ -298,7 +298,7 @@ proc startListeningToEvents*(g: OnchainGroupManager): Future[void] {.async.} =
let newHeadCallback = g.getNewHeadCallback() let newHeadCallback = g.getNewHeadCallback()
try: try:
discard await ethRpc.subscribeForBlockHeaders(newHeadCallback, newHeadErrCallback) discard await ethRpc.subscribeForBlockHeaders(newHeadCallback, newHeadErrCallback)
except: except CatchableError:
raise newException(ValueError, "failed to subscribe to block headers: " & getCurrentExceptionMsg()) raise newException(ValueError, "failed to subscribe to block headers: " & getCurrentExceptionMsg())
proc startOnchainSync*(g: OnchainGroupManager, fromBlock: BlockNumber = BlockNumber(0)): Future[void] {.async.} = proc startOnchainSync*(g: OnchainGroupManager, fromBlock: BlockNumber = BlockNumber(0)): Future[void] {.async.} =
@ -306,13 +306,13 @@ proc startOnchainSync*(g: OnchainGroupManager, fromBlock: BlockNumber = BlockNum
try: try:
await g.getEventsAndSeedIntoTree(fromBlock, some(fromBlock)) await g.getEventsAndSeedIntoTree(fromBlock, some(fromBlock))
except: except CatchableError:
raise newException(ValueError, "failed to get the history/reconcile missed blocks: " & getCurrentExceptionMsg()) raise newException(ValueError, "failed to get the history/reconcile missed blocks: " & getCurrentExceptionMsg())
# listen to blockheaders and contract events # listen to blockheaders and contract events
try: try:
await g.startListeningToEvents() await g.startListeningToEvents()
except: except CatchableError:
raise newException(ValueError, "failed to start listening to events: " & getCurrentExceptionMsg()) raise newException(ValueError, "failed to start listening to events: " & getCurrentExceptionMsg())
proc persistCredentials*(g: OnchainGroupManager): GroupManagerResult[void] = proc persistCredentials*(g: OnchainGroupManager): GroupManagerResult[void] =
@ -358,7 +358,7 @@ method startGroupSync*(g: OnchainGroupManager): Future[void] {.async.} =
# Get archive history # Get archive history
try: try:
await startOnchainSync(g) await startOnchainSync(g)
except: except CatchableError:
raise newException(ValueError, "failed to start onchain sync service: " & getCurrentExceptionMsg()) raise newException(ValueError, "failed to start onchain sync service: " & getCurrentExceptionMsg())
if g.ethPrivateKey.isSome() and g.idCredentials.isNone(): if g.ethPrivateKey.isSome() and g.idCredentials.isNone():
@ -393,7 +393,7 @@ method init*(g: OnchainGroupManager): Future[void] {.async.} =
# check if the Ethereum client is reachable # check if the Ethereum client is reachable
try: try:
ethRpc = await newWeb3(g.ethClientUrl) ethRpc = await newWeb3(g.ethClientUrl)
except: except CatchableError:
raise newException(ValueError, "could not connect to the Ethereum client") raise newException(ValueError, "could not connect to the Ethereum client")
# Set the chain id # Set the chain id
@ -416,7 +416,7 @@ method init*(g: OnchainGroupManager): Future[void] {.async.} =
var membershipFee: Uint256 var membershipFee: Uint256
try: try:
membershipFee = await contract.MEMBERSHIP_DEPOSIT().call() membershipFee = await contract.MEMBERSHIP_DEPOSIT().call()
except: except CatchableError:
raise newException(ValueError, "could not get the membership deposit") raise newException(ValueError, "could not get the membership deposit")
@ -445,7 +445,7 @@ method init*(g: OnchainGroupManager): Future[void] {.async.} =
info "reconnecting with the Ethereum client, and restarting group sync", fromBlock = fromBlock info "reconnecting with the Ethereum client, and restarting group sync", fromBlock = fromBlock
try: try:
asyncSpawn g.startOnchainSync(fromBlock) asyncSpawn g.startOnchainSync(fromBlock)
except: except CatchableError:
error "failed to restart group sync", error = getCurrentExceptionMsg() error "failed to restart group sync", error = getCurrentExceptionMsg()
g.initialized = true g.initialized = true