strconv.ErrSyntax
GoERRORCommonParsing

invalid syntax

Quick Answer

Use errors.Is(err, strconv.ErrSyntax) to detect invalid input and return a user-facing validation error.

What this means

Returned by strconv parsing functions when the input string is not a valid representation of the target type, such as "abc" parsed as an integer.

Why it happens
  1. 1Non-numeric characters in a string passed to ParseInt or ParseFloat
  2. 2Empty string or whitespace-only input passed to a strconv function

Fix

Detect and validate

Detect and validate
n, err := strconv.Atoi(s)
if errors.Is(err, strconv.ErrSyntax) {
    return fmt.Errorf("not a number: %q", s)
}

Why this works

Returning a descriptive error message guides the user to provide valid numeric input.

Code examples
Detectgo
_, err := strconv.Atoi("abc")
if errors.Is(err, strconv.ErrSyntax) {
    fmt.Println("invalid integer")
}
Parse floatgo
f, err := strconv.ParseFloat(s, 64)
if errors.Is(err, strconv.ErrSyntax) {
    return 0, fmt.Errorf("bad float: %q", s)
}
Trim before convertgo
s = strings.TrimSpace(s)
n, err := strconv.Atoi(s)
Sources
Official documentation ↗

Go standard library

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Go errors