💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
## 创建自定义错误 创建自定义错误最简单的方法是使用 errors 包中的 New 函数 errors包New函数的具体实现: ~~~go package errors // New returns an error that formats as the given text. func New(text string) error { return &errorString{text} } // errorString is a trivial implementation of error. type errorString struct { s string } func (e *errorString) Error() string { return e.s } ~~~ ## 用法 1. 使用 New 函数创建自定义错误 `errors.New("Area calculation failed, radius is less than zero")` 2. 使用 Error 添加更多错误信息 `fmt.Errorf("Area calculation failed, radius %0.2f is less than zero", radius) ` 3. 自定义结构体实现error接口 ``` type areaError struct { err string radius float64 } func (e *areaError) Error() string { return fmt.Sprintf("radius %0.2f: %s", e.radius, e.err) } // 调用 &areaError{"radius is negative", radius} ``` 4. 使用结构体类型的方法来提供错误的更多信息 ~~~go 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) } ~~~