Home >Backend Development >Golang >How does golang return error information?

How does golang return error information?

PHPz
PHPzOriginal
2024-04-22 14:03:01879browse

Returning error information in Go: Use the error type to represent error information. Use errors.New() to create simple error messages. Use fmt.Errorf() to create detailed error messages. Errors are caught via if err != nil and handled via fmt.Println(err).

How does golang return error information?

Returning error information in Go

In Go, you can use the error type to represent error information . The following code shows how to return an error message:

func myFunc() error {
  // 出现错误时,使用 errors.New() 创建错误并返回
  return errors.New("some error occurred")
}

You can also create a more detailed error message using the fmt.Errorf() function:

func myFunc() error {
  return fmt.Errorf("some error occurred: %v", someVariable)
}

Capture and handle errors Information:

func main() {
  err := myFunc()
  if err != nil {
    // 处理错误
    fmt.Println(err)
  }
}

Practical case:

In the following example, we return an error in the function and capture it in the main function Handle it:

func readFile(filename string) error {
  file, err := os.Open(filename)
  if err != nil {
    return err
  }
  defer file.Close()
  // ...
  return nil
}

func main() {
  err := readFile("non-existent-file.txt")
  if err != nil {
    fmt.Println(err)
  }
}

This way you can handle and communicate the error gracefully to the user.

The above is the detailed content of How does golang return error information?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn