如何在 Golang 中创建自定义错误
Golang 向我们提供了用于打印自定义错误的不同方法。我们将在本文中探讨其中两种方法。
第一种方法需要我们利用 error.New() 函数,它将创建一个新错误,甚至可以在其中传递我们选择的字符串作为参数。
示例 1
考虑下面显示的代码。
package main
import (
"errors"
"fmt"
"math"
)
func areaOfCircle(radius float64) (float64, error) {
if radius < 0 {
return 0, errors.New("Area calculation wrong, the radius is < zero")
}
return math.Pi * radius * radius, nil
}
func main() {
radius := -10.0
area, err := areaOfCircle(radius)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Area of circle %0.2f", area)
}在上面的代码中,我们尝试找到圆的面积,但是我们传递的半径是负值,这将返回我们在 areaOfCircle 函数中创建的错误。
输出
如果我们在上面的代码中运行命令 go run main.go,我们将在终端中获得以下输出。
Area calculation wrong, the radius is < zero
示例 2
另一种方法是利用 fmt.Errorf(),借助它,我们也可以传递格式化的值。
考虑下面显示的代码。
package main
import (
"fmt"
"math"
)
func areaOfCircle(radius float64) (float64, error) {
if radius < 0 {
return 0, fmt.Errorf("Area calculation wrong, the radius %0.2f is < zero", radius)
}
return math.Pi * radius * radius, nil
}
func main() {
radius := -10.0
area, err := areaOfCircle(radius)
if err != nil {
fmt.Println(err)
return
}
fmt.Printf("Area of circle %0.2f", area)
}输出
如果我们在上面的代码中运行命令 go run main.go,我们将在终端中获得以下输出。
Area calculation wrong, the radius -10.00 is < zero
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP