The introduction of

I’m sure you’ve encountered built-in error types when writing Go code. The Go code uses error to indicate the exception status. For example, err will be non-nil if you use the os.Open function but Go cannot Open the file.

func Open(name string) (file *File, err error)
Copy the code

The following code is used to catch errors when opening files in os.open. If an error occurs, it calls log.fatal to print an error message and stop the program.

f, err := os.Open("filename.ext")
iferr ! =nil {
    log.Fatal(err)
}
Copy the code

In programming languages, the term Exception usually describes a data structure that stores information about an Exception. A common mechanism for exception handling is the transfer of control. Raise a Raise Exception (also called a throw Exception in some languages). After an exception is thrown, control is transferred to a catch somewhere and processing is performed.

If we do not handle exceptions, we may affect the user experience (for example, giving the user access to information that should not be accessible, or crashing the application). Catching and handling exceptions is routine for programmers, and after that, of course, most of us upload exception information to the server for subsequent analysis.

Go Error capture

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

The error type is an interface type, and this is its definition:

type error interface {
    Error() string
}
Copy the code

We can generate error messages in our coding by implementing the error interface type.

The function usually returns an error message in the final return value. Errors. New returns an error message:

func Sqrt(f float64) (float64, error) {
    if f < 0 {
        return 0, errors.New("math: square root of negative number")}}Copy the code