converter error handling
This commit is contained in:
parent
0e5b3a9dc2
commit
f3eada70a8
@ -12,5 +12,9 @@ func main() {
|
||||
input := os.Args[1]
|
||||
convTo := os.Args[2]
|
||||
|
||||
fmt.Println(converter.Convert(input, convTo))
|
||||
result, err := converter.Convert(input, convTo)
|
||||
if err != nil {
|
||||
log.Fatalln(err)
|
||||
}
|
||||
fmt.Println(result)
|
||||
}
|
||||
|
@ -1,7 +1,7 @@
|
||||
package converter
|
||||
|
||||
import "errors"
|
||||
import "fmt"
|
||||
import "log"
|
||||
import "strconv"
|
||||
import "strings"
|
||||
|
||||
@ -22,7 +22,7 @@ var (
|
||||
convVal float64
|
||||
)
|
||||
|
||||
func Convert(input, convTo string) string {
|
||||
func Convert(input, convTo string) (string, error) {
|
||||
switch {
|
||||
case strings.HasSuffix(input, markerKm):
|
||||
inUnit = markerKm
|
||||
@ -33,11 +33,11 @@ func Convert(input, convTo string) string {
|
||||
case strings.HasSuffix(input, markerMiles):
|
||||
inUnit = markerMiles
|
||||
default:
|
||||
log.Fatalln("Invalid input:", input)
|
||||
return "", errors.New("Invalid input: " + input)
|
||||
}
|
||||
inVal, err = strconv.ParseFloat(input[:len(input)-len(inUnit)], 64)
|
||||
if err != nil {
|
||||
log.Fatalln("Invalid input number", err)
|
||||
return "", errors.New("Invalid input number (" + err.Error() + ")")
|
||||
}
|
||||
|
||||
switch inUnit {
|
||||
@ -61,8 +61,8 @@ func Convert(input, convTo string) string {
|
||||
case markerMeter:
|
||||
convVal = asMeter
|
||||
default:
|
||||
log.Fatalln("Invalid unit: " + convTo)
|
||||
return "", errors.New("Invalid unit: " + convTo)
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%.2f%s", convVal, convTo)
|
||||
return fmt.Sprintf("%.2f%s", convVal, convTo), nil
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user