Home  >  Article  >  Backend Development  >  golang err to string

golang err to string

WBOY
WBOYOriginal
2023-05-10 10:03:06839browse

Error handling in the Go language is somewhat different from other languages. The error type is usually used to represent the result of a function. If the function fails to execute, an error value is returned. In the Go language, there is no exception mechanism, and all errors must be returned and handled. When handling errors, it is often necessary to convert error information into string output or write logs.

There are two ways to convert the error type to string, namely using the Error() method of the error interface and using The Sprintf() function of the fmt package.

Use the Error() method of the error interface

error The interface is a specification that contains a single method Error() string to implement this The type of interface represents an error state. We can use this method to get the string representation of the error.

Sample code:

package main

import (
    "errors"
    "fmt"
)

func main() {
    err := errors.New("发生了一个错误")
    fmt.Println(err.Error())
}

Program output:

发生了一个错误

This converts the error type into a string type.

Use fmt.Sprintf() function

In addition to using the Error() method of the error interface to convert errors, we can also use The Sprintf() function in the fmt package formats errors into string output.

Sample code:

package main

import (
    "errors"
    "fmt"
)

func main() {
    err := errors.New("发生了一个错误")
    fmt.Println(fmt.Sprintf("%v", err))
}

Program output:

发生了一个错误

As you can see, using fmt.Sprintf() function output error is different from using The error interface's Error() method outputs the same error content.

Write errors to the log

In addition to outputting error information, we can also write errors to the log file to facilitate troubleshooting later.

Sample code:

package main

import (
    "errors"
    "log"
)

func main() {
    err := errors.New("发生了一个错误")
    log.Println("错误信息:", err)
}

Program output:

2021/08/12 20:06:19 错误信息: 发生了一个错误

As you can see, use the Println() function of the log package Write error information to the log file.

Summary

In Go language, there are two ways to convert the error type into a string, one is to use the error interface## The #Error() method and the Sprintf() function using the fmt package. At the same time, we can also write error information to the log file to facilitate troubleshooting.

The above is the detailed content of golang err to string. 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