Skip to content

Commit

Permalink
fix: improve get peer info errors
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobheun committed Nov 12, 2018
1 parent f71fdfd commit 714b6ec
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 9 deletions.
24 changes: 17 additions & 7 deletions src/get-peer-info.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
const PeerId = require('peer-id')
const PeerInfo = require('peer-info')
const multiaddr = require('multiaddr')
const setImmediate = require('async/setImmediate')
const errCode = require('err-code')

module.exports = (node) => {
/*
Expand All @@ -20,16 +20,21 @@ module.exports = (node) => {
try {
peer = multiaddr(peer)
} catch (err) {
return setImmediate(() => callback(err))
return callback(
errCode(err, 'ERR_INVALID_MULTIADDR')
)
}
}

const peerIdB58Str = peer.getPeerId()

if (!peerIdB58Str) {
return setImmediate(() => {
callback(new Error('peer multiaddr instance or string must include peerId'))
})
return callback(
errCode(
new Error('peer multiaddr instance or string must include peerId'),
'ERR_INVALID_MULTIADDR'
)
)
}

try {
Expand All @@ -48,9 +53,14 @@ module.exports = (node) => {
return node.peerRouting.findPeer(peer, callback)
}
} else {
return setImmediate(() => callback(new Error('peer type not recognized')))
return callback(
errCode(
new Error(`${p} is not a valid peer type`),
'ERR_INVALID_PEER_TYPE'
)
)
}

setImmediate(() => callback(null, p))
callback(null, p)
}
}
12 changes: 10 additions & 2 deletions test/get-peer-info.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,23 @@ describe('getPeerInfo', () => {
it('should callback with error for invalid string multiaddr', (done) => {
getPeerInfo(null)('INVALID MULTIADDR', (err) => {
expect(err).to.exist()
expect(err.message).to.contain('must start with a "/"')
expect(err.code).to.eql('ERR_INVALID_MULTIADDR')
done()
})
})

it('should callback with error for invalid non-peer multiaddr', (done) => {
getPeerInfo(null)('/ip4/8.8.8.8/tcp/1080', (err) => {
expect(err).to.exist()
expect(err.message).to.equal('peer multiaddr instance or string must include peerId')
expect(err.code).to.equal('ERR_INVALID_MULTIADDR')
done()
})
})

it('should callback with error for invalid non-peer multiaddr', (done) => {
getPeerInfo(null)(undefined, (err) => {
expect(err).to.exist()
expect(err.code).to.eql('ERR_INVALID_PEER_TYPE')
done()
})
})
Expand Down

0 comments on commit 714b6ec

Please sign in to comment.