@phper 2018-03-13T10:07:44.000000Z 字数 6128 阅读 2169

# 31.自定义错误

Golang

## 使用New函数创建自定义错误

// Package errors implements functions to manipulate errors.  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  }

package mainimport (      "errors"    "fmt"    "math")func circleArea(radius float64) (float64, error) {      if radius < 0 {        return 0, errors.New("Area calculation failed, radius is less than zero")    }    return math.Pi * radius * radius, nil}func main() {      radius := -20.0    area, err := circleArea(radius)    if err != nil {        fmt.Println(err)        return    }    fmt.Printf("Area of circle %0.2f", area)}

main函数中, 在第19行我们检查错误是否为nil。如果不是nil, 则打印错误并返回, 否则将打印圆的面积。

Area calculation failed, radius is less than zero


## 使用Errorf函数将更多信息添加到错误中

package mainimport (      "fmt"    "math")func circleArea(radius float64) (float64, error) {      if radius < 0 {        return 0, fmt.Errorf("Area calculation failed, radius %0.2f is less than zero", radius)    }    return math.Pi * radius * radius, nil}func main() {      radius := -20.0    area, err := circleArea(radius)    if err != nil {        fmt.Println(err)        return    }    fmt.Printf("Area of circle %0.2f", area)}

Area calculation failed, radius -20.00 is less than zero


## 使用结构类型和字段提供有关错误的更多信息

type areaError struct {      err    string    radius float64}

func (e *areaError) Error() string {      return fmt.Sprintf("radius %0.2f: %s", e.radius, e.err)}

package mainimport (      "fmt"    "math")type areaError struct {      err    string    radius float64}func (e *areaError) Error() string {      return fmt.Sprintf("radius %0.2f: %s", e.radius, e.err)}func circleArea(radius float64) (float64, error) {      if radius < 0 {        return 0, &areaError{"radius is negative", radius}    }    return math.Pi * radius * radius, nil}func main() {      radius := -20.0    area, err := circleArea(radius)    if err != nil {        if err, ok := err.(*areaError); ok {            fmt.Printf("Radius %0.2f is less than zero", err.radius)            return        }        fmt.Println(err)        return    }    fmt.Printf("Area of rectangle1 %0.2f", area)}

Radius -20.00 is less than zero


## 使用结构类型上的方法提供有关错误的更多信息

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)}

package mainimport "fmt"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)}

error: length -5.00 is less than zero  error: width -9.00 is less than zero  

• 使用新函数创建自定义错误
• 使用 Errorf 将更多信息添加到错误中
• 使用结构类型和字段提供有关错误的更多信息
• 使用结构类型上的方法提供有关错误的更多信息
祝你今天开心。

• 私有
• 公开
• 删除