We need to write a good error handling, usually in the avoid some programmers abuse disorders, so Go here to cut off the exception that directly, ultimately through the return value to judge the abnormal situation of the program, Go, after all, but supports multiple return values of language, such as atoi, itoa function, the second return value can’t ignore it, Because the second return value represents whether the conversion was successful! However, Golang does provide some error-handling mechanisms

Wrong mechanism for Go

1. No exception mechanism

The error type implements the error interface

3. You can quickly create error instances with errors.New

type error interface{
    Error() string
}

error.New("n must be in range[0, 1]")
Copy the code

But all it does is give the developer an identity. How does Code know that? Do you want to go to string? Of course not, there are some predefined errors:

Best practices for handling errors

1. Predefined errors are judged in code

2, early failure, avoid nesting

Panic and recover

Panic is used for unrecoverable errors, similar to Java’s Error

Before Panic exits, the content specified by defer will be executed

Panic and OS. The Exit

The functions specified by defer will not be called when os.Exit exits

Os. Exit Does not output the current call stack information when exiting

So let’s look at Recover

In Java, if you don’t know what error to throw, a lot of people just throw a Catch Throwable, as an exception without Fack. As an exception no Fack said

Some error-recovery behavior can be performed in the Go language through the functions defined by defer

Many people tend to print the error object recovered gets into the log file when defer handles the error. This is a very dangerous practice. Be careful what Recover is doing, because recover does not detect what exactly happened, but simply ignores the error. So this time if the system is the core of resource consumption, if our mandatory recovery system is still not working, can also lead to our health check program can’t check out the current problems in the system, because a lot of the health check is the check in process or not, because we are in the process of, As a result, zombie service processes are alive but unable to provide services properly. So we can use one of the recovery design patterns called Let It Crash, and the Health Check process will restart the service for us