Skip to content

Commit

Permalink
fix: throw on bad version with correct error message (#552)
Browse files Browse the repository at this point in the history
  • Loading branch information
wraithgar committed Apr 17, 2023
1 parent 503a4e5 commit e219bb4
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 16 deletions.
2 changes: 1 addition & 1 deletion classes/semver.js
Expand Up @@ -16,7 +16,7 @@ class SemVer {
version = version.version
}
} else if (typeof version !== 'string') {
throw new TypeError(`Invalid Version: ${version}`)
throw new TypeError(`Invalid Version: ${require('util').inspect(version)}`)
}

if (version.length > MAX_LENGTH) {
Expand Down
6 changes: 3 additions & 3 deletions functions/diff.js
@@ -1,8 +1,8 @@
const parse = require('./parse')
const parse = require('./parse.js')

const diff = (version1, version2) => {
const v1 = parse(version1)
const v2 = parse(version2)
const v1 = parse(version1, null, true)
const v2 = parse(version2, null, true)
const comparison = v1.compare(v2)

if (comparison === 0) {
Expand Down
17 changes: 5 additions & 12 deletions functions/parse.js
@@ -1,22 +1,15 @@
const { MAX_LENGTH } = require('../internal/constants')
const SemVer = require('../classes/semver')
const parse = (version, options) => {
const parse = (version, options, throwErrors = false) => {
if (version instanceof SemVer) {
return version
}

if (typeof version !== 'string') {
return null
}

if (version.length > MAX_LENGTH) {
return null
}

try {
return new SemVer(version, options)
} catch (er) {
return null
if (!throwErrors) {
return null
}
throw er
}
}

Expand Down
10 changes: 10 additions & 0 deletions test/functions/diff.js
Expand Up @@ -43,3 +43,13 @@ test('diff versions test', (t) => {

t.end()
})

test('throws on bad version', (t) => {
t.throws(() => {
diff('bad', '1.2.3')
}, {
message: 'Invalid Version: bad',
name: 'TypeError',
})
t.end()
})
16 changes: 16 additions & 0 deletions test/functions/parse.js
Expand Up @@ -9,6 +9,22 @@ t.test('returns null instead of throwing when presented with garbage', t => {
t.equal(parse(v, opts), null, msg))
})

t.test('throw errors if asked to', t => {
t.throws(() => {
parse('bad', null, true)
}, {
name: 'TypeError',
message: 'Invalid Version: bad',
})
t.throws(() => {
parse([], null, true)
}, {
name: 'TypeError',
message: 'Invalid Version: []',
})
t.end()
})

t.test('parse a version into a SemVer object', t => {
t.match(parse('1.2.3'), new SemVer('1.2.3'))
const s = new SemVer('4.5.6')
Expand Down

0 comments on commit e219bb4

Please sign in to comment.