Skip to main content

错误 Errors

Golang 中的错误处理方式会让我们自动考虑如何处理错误情况。

func main() {
user, err := getUser()
if err != nil {
fmt.Println(err)
return
}

profile, err := getUserProfile(user.ID)
if err != nil {
fmt.Prinln(err)
return
}
}

Definition

An Error is any type that implements the simple built-in error interface:

type error interface {
Error() string
}
i, err := strconv.Atoi("42b")
if err != nil {
fmt.Prinln("couldn't convert:", err)
return
}

Build own error interface

type userError struct {
name string
}

func (e userError) Error() string {
return fmt.Sprintf("%v has a problem with their account", e.name)
}

func sendSMS(msg, userName string) error {
if !canSendToUser(userName) {
return userError{name: userName}
}
}

The built-in Errors packages

import "errors"

var err error = errors.New("something went wrong")