SoFunction
Updated on 2025-03-04

Several ways to deal with Go errors

Overview

existPrevious SectionIn the content of this, we introduce Go's interface, including: defining interfaces, implementing interfaces, using interfaces, empty interfaces, etc. In this section, we will introduce Go's error handling. In Go, error handling is an important programming mode that is used to handle possible errors or exceptions. Go adopts a concise and direct error handling method. By using built-in error types and convention return values, developers can effectively handle and pass error messages.

errors package

The errors package in Go language is mainly used for error handling. It provides some simple interfaces and functions for creating and manipulating error values. Below, we introduce some common functions in the errors package.

Create an error: You can use the() function to create a simple error value. It accepts a string parameter to represent error messages. for example:

err := ("something is wrong")

Packaging error: You can use the() function to wrap an error value. It accepts an error value and a string parameter, and returns a new error value containing the details of the original error. for example:

err := (originalError, "something is wrong")

Get error message: You can use the() function to get the original error in the wrapping error. It accepts an error value, returning the original error. for example:

originalErr := (err)

Determine error type: You can use the() function to determine whether an error belongs to a specific type. It accepts an error value and a type parameter, returning a boolean value indicating whether it matches or not. for example:

if (err, )

Error formatting: You can use the() function to create a formatted error value. It accepts a formatted string and variable parameters, similar to the() function. for example:

err := ("something is wrong: %s", errorMessage)

Return an error

In Go language, the last return value of the function is usually defined as an error type, which indicates whether an error occurred during the execution of the function. If the function executes successfully, the error value is nil; if the function executes failed, the corresponding error value is assigned to the error variable. This convention allows the caller of the function to easily check whether the function returns an error and take corresponding measures as needed.

In the following example code, the divide function takes two float64 parameters and returns a float64 result and an error type error. When the divisor is zero, the function returns a non-zero error value to describe the error message. In the main function, we determine whether the function is executed successfully by checking whether the error variable err is nil. If err is not nil, it means that the function execution failed and the corresponding error message is printed; otherwise, the result of the function execution is printed.

package main

import "fmt"
import "errors"
  
func divide(a, b float64) (float64, error) {
    if b == 0 {
        return 0, ("divisor cannot be zero")
    }

    return a / b, nil
}

func main() {
    result, err := divide(10, 2)
    if err != nil {
        ("Error:", err)
    } else {
        // Output: Result: 5        ("Result:", result)
    }

    result, err = divide(10, 0)
    if err != nil {
        // Output: Error: divisor cannot be zero        ("Error:", err)
    } else {
        ("Result:", result)
    }
}

In addition to directly returning the error value, you can also use multiple return values ​​to perform error handling inside the function. In the following example code, we use an extra variable to indicate whether the function executes successfully.

package main  
  
import "fmt"
import "errors"
  
func divide(a, b float64) (float64, bool, error) {
    if b == 0 {
        return 0, false, ("divisor cannot be zero")
    }

    if b == 1 {
        return 0, false, nil
    }

    return a / b, true, nil
}  
  
func main() {
    result, success, err := divide(10, 1)
    if err != nil {
        ("Error:", err)
    } else if !success {
        // Output: divisor cannot be 1        ("divisor cannot be 1")
    } else {
        ("Result:", result)
    }
}

throw an exception

In Go, panic function can be used to throw exceptions. The panic function is a built-in function that indicates that an unrecoverable error occurred. When the panic function is called, execution of the current function will stop immediately and the stack will be called recursively until the appropriate defer statement or function returns.

panic functions are usually used to handle errors that cannot be processed, such as: memory overflow, null pointer reference, etc. When the panic function is called, it passes a string as a parameter indicating the cause of the error, which can be captured and used for error handling or logging.

In the following example code, we throw an exception using the panic function. Before executing the panic function, the output string "before panic" is printed. After executing the panic function, the execution of the main function will stop immediately, so the subsequent print statement will not continue to be executed.

package main

import "fmt"

func main() {
    // Output: before panic    ("before panic")

    // throw an exception    panic("an exception occured")

    // The following statement will not be executed    ("after panic")
}

Catch exceptions

In Go, you can use the recover function and defer keyword to catch exceptions.

The recover function is a built-in function that is used to recover from a panic exception and continue executing the program. When a program encounters a panic, it interrupts the current execution process and starts propagating the panic to the upper call stack until it is captured or the program terminates. The recover function allows panic exceptions to be caught and processed in defer keyword modified functions so that the program can continue execution without terminating.

The defer keyword is used to delay execution of a function call until the function containing it is executed before it is returned. A function call modified by defer will be pushed into a stack, and the function call will be popped out of the stack and executed until the function containing it returns. The defer keyword is usually used to perform some cleaning operations before the function returns, such as closing files, freeing resources, printing logs, etc. It can be used to ensure that the relevant resources are correctly released at the end of the function execution, avoiding resource leakage problems.

Note: The recover function can only be used in the defer function and cannot be used in other contexts. When recover is called in the defer function, it stops panic propagation and returns the value of panic (if any). If no panic occurs, the recover function returns nil.

In the following example code, we use the defer keyword and anonymous function to create a defer function. In the defer function, we call the recover function to catch the panic exception. If panic occurs, we will print out the corresponding error message.

package main

import "fmt"

func main() {
    defer func() {
        if r := recover(); r != nil {
            //Catch an exception, output: an exception caught: an exception occurred            ("an exception caught:", r)
        }
    }()

    // Output: before panic    ("before panic")

    // throw an exception    panic("an exception occured")

    // The following statement will not be executed    ("after panic")
}

This is the end of this article about several ways to deal with Go errors. For more related Go errors, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!