Latest web development tutorials

Go error handling

Go language provides a very simple error handling mechanism through built-in error interface.

error type is an interface type, which is its definition:

type error interface {
    Error() string
}

We can implement error interface type to generate an error message in the code.

Function generally returns an error message at the end of the return value. Use errors.New returns an error message:

func Sqrt(f float64) (float64, error) {
    if f < 0 {
        return 0, errors.New("math: square root of negative number")
    }
    // 实现
}

In the following example, we call the Sqrt when passing a negative number, then you get the error object is non-nil, compared with this object nil, the result is true, so fmt.Println (fmt package when handling error error will be called method) is called to output error, see the following sample code calls:

result, err:= Sqrt(-1)

if err != nil {
   fmt.Println(err)
}

Examples

package main

import (
	"fmt"
)

// 定义一个 DivideError 结构
type DivideError struct {
	dividee int
	divider int
}

// 实现 	`error` 接口
func (de *DivideError) Error() string {
	strFormat := `
	Cannot proceed, the divider is zero.
	dividee: %d
	divider: 0
`
	return fmt.Sprintf(strFormat, de.dividee)
}

// 定义 `int` 类型除法运算的函数
func Divide(varDividee int, varDivider int) (result int, errorMsg string) {
	if varDivider == 0 {
		dData := DivideError{
			dividee: varDividee,
			divider: varDivider,
		}
		errorMsg = dData.Error()
		return
	} else {
		return varDividee / varDivider, ""
	}

}

func main() {

	// 正常情况
	if result, errorMsg := Divide(100, 10); errorMsg == "" {
		fmt.Println("100/10 = ", result)
	}
	// 当被除数为零的时候会返回错误信息
	if _, errorMsg := Divide(100, 0); errorMsg != "" {
		fmt.Println("errorMsg is: ", errorMsg)
	}

}

The above program, the output is:

100/10 =  10
errorMsg is:  
	Cannot proceed, the divider is zero.
	dividee: 100
	divider: 0