Go - Error Handling

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

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

type error interface {
    Error() string

We can generate error messages in the encoding by the achieve error interface type.

The function usually returns an error message in the last return value. Use errors.New to return an error message:

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 pass a negative number when calling Sqrt, and then we get the non-nil error object, compare this object with nil, the result is true, so fmt.Println(fmt package When the error is handled, the Error method is called) is called to output the error. Please see the sample code called below:

result, err:= Sqrt(-1)

if err != nil {


package main

import (

// Define a DivideError structure
type DivideError struct {
    dividee int
    divider int

// Implement `error` interface
func (de *DivideError) Error() string {
    strFormat := `
    Cannot proceed, the divider is zero.
    dividee: %d
    divider: 0

    return fmt.Sprintf(strFormat, de.dividee)

// a function that defines the `int` type division operation
func Divide(varDividee int, varDivider int) (result int, errorMsg string) {
    if varDivider == 0 {
            dData := DivideError{
                    dividee: varDividee,
                    divider: varDivider,
            errorMsg = dData.Error()
    } else {
            return varDividee / varDivider, ""


func main() {

    // normal circumstances
    if result, errorMsg := Divide(100, 10); errorMsg == "" {
            fmt.Println("100/10 = ", result)
    // An error message is returned when the dividend is zero
    if _, errorMsg := Divide(100, 0); errorMsg != "" {
            fmt.Println("errorMsg is: ", errorMsg)


Execute the above program, the output is:

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