How does golang return error information?

PHPz
Release: 2024-04-22 14:03:01
Original
828 people have browsed it

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")
}
Copy after login

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)
}
Copy after login

Capture and handle errors Information:

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

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)
  }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template