1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

semver: add custom errors (#9493)

This commit is contained in:
Atakan Yenel 2021-03-29 11:17:00 +02:00 committed by GitHub
parent cabbf93faa
commit 89082de5d1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 51 additions and 6 deletions

20
examples/errors.v Normal file
View File

@ -0,0 +1,20 @@
import semver
fn main() {
semver.from('asd') or { check_error(err) }
semver.from('') or { check_error(err) }
}
fn check_error(err IError) {
match err {
semver.InvalidVersionFormatError {
println('wrong format')
}
semver.EmptyInputError {
println('empty input')
}
else {
println('unknown error')
}
}
}

View File

@ -29,6 +29,16 @@ struct Range {
comparator_sets []ComparatorSet
}
struct InvalidComparatorCountError {
msg string
code int
}
struct InvalidComparatorFormatError {
msg string
code int
}
fn (r Range) satisfies(ver Version) bool {
mut final_result := false
for set in r.comparator_sets {
@ -74,12 +84,16 @@ fn parse_range(input string) ?Range {
fn parse_comparator_set(input string) ?ComparatorSet {
raw_comparators := input.split(semver.comparator_sep)
if raw_comparators.len > 2 {
return error('Invalid format of comparator set for input "$input"')
return IError(&InvalidComparatorFormatError{
msg: 'Invalid format of comparator set for input "$input"'
})
}
mut comparators := []Comparator{}
for raw_comp in raw_comparators {
c := parse_comparator(raw_comp) or {
return error('Invalid comparator "$raw_comp" in input "$input"')
return IError(&InvalidComparatorFormatError{
msg: 'Invalid comparator "$raw_comp" in input "$input"'
})
}
comparators << c
}

View File

@ -19,15 +19,27 @@ pub enum Increment {
patch
}
struct EmptyInputError {
msg string = 'Empty input'
code int
}
struct InvalidVersionFormatError {
msg string
code int
}
// * Constructor.
// from returns a `Version` structure parsed from `input` `string`.
pub fn from(input string) ?Version {
if input.len == 0 {
return error('Empty input')
return IError(&EmptyInputError{})
}
raw_version := parse(input)
version := raw_version.validate() or {
return error('Invalid version format for input "$input"')
return IError(&InvalidVersionFormatError{
msg: 'Invalid version format for input "$input"'
})
}
return version
}
@ -88,8 +100,7 @@ v := semver.coerce('1.3-RC1-b2') or { semver.Version{} }
assert v.satisfies('>1.0 <2.0') == true // 1.3.0
*/
pub fn coerce(input string) ?Version {
ver := coerce_version(input) or { return error('Invalid version for input "$input"') }
return ver
return coerce_version(input)
}
// is_valid returns `true` if the `input` `string` can be converted to