E Tech.

Go Error Memo

Error handling

1. Simple Failure

In this case, the caller doesn't need to branch on the error. Just check whether an error occurred.

func ReturnSimple() (string, error){
    return "", errors.New("this is simple error just value")  //just a message
}

_, err := ReturnSimple()
if err!=nil{
    //fmt.Println(err) or
    //os.Exit(1)
}

2. Simple Custom Error(Sentinel Error)

Define an error value and check it with errors.Is(). Export the error so callers can use it, and keep errors consistent within the package.

var ErrNotFound = errors.New("not found")
func readFile(path string)(File, error){
    //There is no file to read
    return File{}, fmt.Errorf("read %s: %w", path, ErrNotFound)
}

func EditFile(path string){
    file, err := readFile("./text.txt")
    if errors.Is(err, ErrNotFound){  //errors.Is can detect wrapped ErrNotFound
        //do something, like create a new file
    }
}

3. Complex Custom Error

Analyze the error details and handle it using the fields of the error struct.

type ConnectionError struct {
    WaitTime int
}

func (e *ConnectionError) Error() string {
    return fmt.Sprintf("connection failed, wait %d", e.WaitTime)
}

func GetOriginalResponse()(Response, error){
    //something fails
    return Response{}, fmt.Errorf("get response: %w", &ConnectionError{WaitTime:100})
}

res, err := GetOriginalResponse()

var ce *ConnectionError
if errors.As(err, &ce) {
    if ce.WaitTime <= 50{
        //do something
    }else if ce.WaitTime <= 100 {
        //do something
    }else{
        //...
    }
}

Reference

Leapcell - The Subtle Art of Error Creation: Understanding errors.New and fmt.Errorf in Go