32 Error Wrapping

43 阅读1分钟

Error wrapping is the process of encapsulating one error into another.

package main

import (
	"errors"
	"fmt"
)

var noRows = errors.New("no rows found")

func getRecord() error {
	return noRows
}

func webService() error {
	if err := getRecord(); err != nil {
		return fmt.Errorf("Error %s when calling DB", err)
	}
	return nil
}

func main() {
	if err := webService(); err != nil {
		fmt.Printf("Error: %s when calling webservice\n", err)
		return
	}
	fmt.Println("webservice call successful")

}

Error wrapping and the Is function

The Is function in the errors package reports whether any of the errors in the chain matches the target.

package main

import (
	"errors"
	"fmt"
)

var noRows = errors.New("no rows found")

func getRecord() error {
	return noRows
}

func webService() error {
	if err := getRecord(); err != nil {
		return fmt.Errorf("Error %w when calling DB", err)
	}
	return nil
}

func main() {
	if err := webService(); err != nil {
		if errors.Is(err, noRows) {
			fmt.Printf("The searched record cannot be found. Error returned from DB is %s", err)
			return
		}
		fmt.Println("unknown error when searching record")
		return

	}
	fmt.Println("webservice call successful")

}
The searched record cannot be found. Error returned from DB is Error no rows found when calling DB

As function

As function

The As in the errors package will try to convert the error that is passed as input to the target error type. It will succeed if any of the error in the error chain matches the target. If it’s successful it will return true, and it will set the target to the first error in the error chain that matches. A program will make things easier to understand :)

package main

import (
	"errors"
	"fmt"
)

type DBError struct {
	desc string
}

func (dbError DBError) Error() string {
	return dbError.desc
}

func getRecord() error {
	return DBError{
		desc: "no rows found",
	}
}

func webService() error {
	if err := getRecord(); err != nil {
		return fmt.Errorf("Error %w when calling DB", err)
	}
	return nil
}

func main() {
	if err := webService(); err != nil {
		var dbError DBError
		if errors.As(err, &dbError) {
			fmt.Printf("The searched record cannot be found. Error returned from DB is %s", dbError)
			return
		}
		fmt.Println("unknown error when searching record")
		return

	}
	fmt.Println("webservice call successful")

}