// use the type asserting to get more informationfuncopen_error(){f,err:=os.Open("tet")iferr!=nil{fmt.Printf("Err:%v, type:%T, path: %v\n",err,err)return}fmt.Println("Open succeccfully",f.Name())}
// package errors to implements functions to manipulate errors.
package errors
// return an error that formats as the given text.
func New(s string) error {
return &errorString{s}
}
// errorString is a trivial implementation of error.
type errorString struct {
s string
}
// implements the error interface, so the variable
// can be assigned to error type.
func (e *errorString) Error() string {
return e.s
}
// use the errors.New get a errorString error
func circleArea(radius float64) (float64, error) {
if radius < 0 {
return 0, errors.New("The radius must not be be negative")
}
return math.Pi * radius * radius, nil
}
// use the fmt.Errorf to get same function
func rectanglArea(leng, wid float64) (float64, error) {
if leng < 0 {
return 0, fmt.Errorf("Given length of rectangle %v is not correct\n", leng)
}
if wid < 0 {
return 0, fmt.Errorf("Given width of rectangle %v is not correct\n", wid)
}
return leng * wid, nil
}
type areaError struct {
err string
radius float64
}
func (e *areaError) Error() string {
return fmt.Sprintf("radius %0.2f: %s", e.radius, e.err)
}
// use the errors.New get a errorString error
func circleArea(radius float64) (float64, error) {
if radius < 0 {
return 0, &areaError{"is nagative", radius}
}
return math.Pi * radius * radius, nil
}
func main() {
radius := -20.
var holder error
area, err := circleArea(radius)
if err != nil {
holder = err // 此处得到的err是一个指针类型,使用指针类型是为了避免不必要的参数复制
fmt.Printf("%v, %T\n", holder, holder)
} else {
fmt.Println("Area of the circle:", area)
}
}
/*radius -20.00: is nagative, *main.areaError*/
type areaError struct {
err string //error description
length float64 //length which caused the error
width float64 //width which caused the error
}
func (e *areaError) Error() string {
return e.err
}
func (e *areaError) lengthNegative() bool {
return e.length < 0
}
func (e *areaError) widthNegative() bool {
return e.width < 0
}
func rectArea(length, width float64) (float64, error) {
err := ""
if length < 0 {
err += "length is less than zero"
}
if width < 0 {
if err == "" {
err = "width is less than zero"
} else {
err += ", width is less than zero"
}
}
if err != "" {
return 0, &areaError{err, length, width}
}
return length * width, nil
}
func main() {
length, width := -5.0, -9.0
area, err := rectArea(length, width)
if err != nil {
if err, ok := err.(*areaError); ok {
if err.lengthNegative() {
fmt.Printf("error: length %0.2f is less than zero\n", err.length)
}
if err.widthNegative() {
fmt.Printf("error: width %0.2f is less than zero\n", err.width)
}
return
}
fmt.Println(err)
return
}
fmt.Println("area of rect", area)
}