converter error handling

This commit is contained in:
Meutel 2017-07-09 10:48:34 +02:00
parent 0e5b3a9dc2
commit f3eada70a8
2 changed files with 11 additions and 7 deletions

View File

@ -12,5 +12,9 @@ func main() {
input := os.Args[1] input := os.Args[1]
convTo := os.Args[2] 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)
} }

View File

@ -1,7 +1,7 @@
package converter package converter
import "errors"
import "fmt" import "fmt"
import "log"
import "strconv" import "strconv"
import "strings" import "strings"
@ -22,7 +22,7 @@ var (
convVal float64 convVal float64
) )
func Convert(input, convTo string) string { func Convert(input, convTo string) (string, error) {
switch { switch {
case strings.HasSuffix(input, markerKm): case strings.HasSuffix(input, markerKm):
inUnit = markerKm inUnit = markerKm
@ -33,11 +33,11 @@ func Convert(input, convTo string) string {
case strings.HasSuffix(input, markerMiles): case strings.HasSuffix(input, markerMiles):
inUnit = markerMiles inUnit = markerMiles
default: default:
log.Fatalln("Invalid input:", input) return "", errors.New("Invalid input: " + input)
} }
inVal, err = strconv.ParseFloat(input[:len(input)-len(inUnit)], 64) inVal, err = strconv.ParseFloat(input[:len(input)-len(inUnit)], 64)
if err != nil { if err != nil {
log.Fatalln("Invalid input number", err) return "", errors.New("Invalid input number (" + err.Error() + ")")
} }
switch inUnit { switch inUnit {
@ -61,8 +61,8 @@ func Convert(input, convTo string) string {
case markerMeter: case markerMeter:
convVal = asMeter convVal = asMeter
default: 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
} }