Go
Beginner
1 min read
Error Handling Fundamentals
Example
package main
import (
"errors"
"fmt"
"strconv"
)
// Custom error type
type ParseError struct {
Input string
Err error
}
func (e *ParseError) Error() string {
return fmt.Sprintf("ParseError: cannot parse %q: %v", e.Input, e.Err)
}
func (e *ParseError) Unwrap() error { return e.Err }
func parsePositive(s string) (int, error) {
n, err := strconv.Atoi(s)
if err != nil {
return 0, &ParseError{Input: s, Err: err}
}
if n <= 0 {
return 0, fmt.Errorf("parsePositive: %d is not positive", n)
}
return n, nil
}
func main() {
inputs := []string{"42", "-5", "abc", "100"}
for _, s := range inputs {
n, err := parsePositive(s)
if err != nil {
// Type assertion
var pe *ParseError
if errors.As(err, &pe) {
fmt.Printf("type error for %q: %v\n", pe.Input, pe.Err)
} else {
fmt.Printf("value error: %v\n", err)
}
continue
}
fmt.Printf("parsed: %d\n", n)
}
}