Go error handling


Release date:2023-09-20 Update date:2023-12-11 Editor:admin View counts:488

Label:

Go error handling

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

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

type error interface {
    Error() string
}

We can implement it in coding by implementing error interface type to generate error messages.

The function usually returns an error message in the final return value. Use``errors.New`` error message can be returned:

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

In the following example, we are calling the Sqrt negative number is passed, and then you get it. non-nil of error object, which is compared to the nil comparison, the result is true so fmt.Println ( fmt bag is being processed. error will be called when Error method is called to output the error, see the sample code called below:

result, err:= Sqrt(-1)

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

Example

Example

package main
import (
    "fmt"
)
// Define a DivideError structure
type DivideError struct {
    dividee int
    divider int
}
// Implement the error interface
func (de *DivideError) Error() string {
    strFormat := \`
    Cannot proceed, the divider is zero.
    dividee: %d
    divider: 0
\`
    return fmt.Sprintf(strFormat, de.dividee)
}
// Define functions for type division operations
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() {
    // normal conditions
    if result, errorMsg := Divide(100, 10); errorMsg == "" {
            fmt.Println("100/10 = ", result)
    }
    // When the divisor is zero, an error message will be returned
    if \_, errorMsg := Divide(100, 0); errorMsg != "" {
            fmt.Println("errorMsg is: ", errorMsg)
    }
}

Execute the above program, and the output is as follows:

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

Powered by TorCMS (https://github.com/bukun/TorCMS).