@@ -6,8 +6,17 @@ const { safeRe: re, t } = require('../internal/re')
66
77const parseOptions = require ( '../internal/parse-options' )
88const { compareIdentifiers } = require ( '../internal/identifiers' )
9+
10+ function handleErrorOnSemver ( semver , errorMessage , throwErrors ) {
11+ if ( throwErrors ) {
12+ throw new TypeError ( errorMessage )
13+ } else {
14+ semver . errorMessage = errorMessage
15+ }
16+ }
17+
918class SemVer {
10- constructor ( version , options ) {
19+ constructor ( version , options , throwErrors = true ) {
1120 options = parseOptions ( options )
1221
1322 if ( version instanceof SemVer ) {
@@ -18,13 +27,11 @@ class SemVer {
1827 version = version . version
1928 }
2029 } else if ( typeof version !== 'string' ) {
21- throw new TypeError ( `Invalid version. Must be a string. Got type "${ typeof version } ".` )
30+ return handleErrorOnSemver ( this , `Invalid version. Must be a string. Got type "${ typeof version } ".` , throwErrors )
2231 }
2332
2433 if ( version . length > MAX_LENGTH ) {
25- throw new TypeError (
26- `version is longer than ${ MAX_LENGTH } characters`
27- )
34+ return handleErrorOnSemver ( this , `version is longer than ${ MAX_LENGTH } characters` , throwErrors )
2835 }
2936
3037 debug ( 'SemVer' , version , options )
@@ -37,7 +44,7 @@ class SemVer {
3744 const m = version . trim ( ) . match ( options . loose ? re [ t . LOOSE ] : re [ t . FULL ] )
3845
3946 if ( ! m ) {
40- throw new TypeError ( `Invalid Version: ${ version } ` )
47+ return handleErrorOnSemver ( this , `Invalid Version: ${ version } ` , throwErrors )
4148 }
4249
4350 this . raw = version
@@ -48,15 +55,15 @@ class SemVer {
4855 this . patch = + m [ 3 ]
4956
5057 if ( this . major > MAX_SAFE_INTEGER || this . major < 0 ) {
51- throw new TypeError ( 'Invalid major version' )
58+ return handleErrorOnSemver ( this , 'Invalid major version' , throwErrors )
5259 }
5360
5461 if ( this . minor > MAX_SAFE_INTEGER || this . minor < 0 ) {
55- throw new TypeError ( 'Invalid minor version' )
62+ return handleErrorOnSemver ( this , 'Invalid minor version' , throwErrors )
5663 }
5764
5865 if ( this . patch > MAX_SAFE_INTEGER || this . patch < 0 ) {
59- throw new TypeError ( 'Invalid patch version' )
66+ return handleErrorOnSemver ( this , 'Invalid patch version' , throwErrors )
6067 }
6168
6269 // numberify any prerelease numeric ids
0 commit comments