strconv.Atoi is called with empty string

575 阅读1分钟

In a project, I transformed a string to int using strconv.Atoi, then check the returned error to print out to log file if an error happened. Because the input data was got by calling a thirdparty api, with forgetting check empty string, the error was like this,

strconv.Atoi: parsing "": invalid syntax

The code snippet is pasted following,

package main

import (
	"fmt"
	"strconv"
)

func main() {
	val := ""
	i, err := strconv.Atoi(val)
	fmt.Println(i, err)
}

So on production environment, the input string argument must be checked to make sure it is not empty, avoiding this type of error.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	val := ""
	if val == "" {
		return
	}
	i, err := strconv.Atoi(val)
	fmt.Println(i, err)
}