When you write a program and it won't behave as the way you expected it may cased by some external factors and that you can't control like other processes blocking a file, or an attempt to access a memory address that not available anymore.
It's better if you anticipate those failures so you can troubleshoot problems when they happen.
Go's approach for exception handling is different, and so is its process for error handling. In Go, a function that could fail should always return an additional value so that you can anticipate and manage a failure successfully. For example, you could run a default behavior and log as much information as possible to reproduce the problem and fix it.
Before starting this make sure you have Go environment ready, you should have installed and configured Go locally and installed Visual Studio Code with the Go extension.
Handle errors in Go
You need to manage your program failures your users don't want to see a long and confusing stack of error record, it's better if they see meaningful information about what went wrong.
Go has built-in functions like panic and recover to manage exceptions, or unexpected behavior, in your programs. But errors are known failures that your programs should be built to handle.
Go's approach to error handling is simply a control-flow mechanism where only an if and a *return * statement are needed.
employee, err := getInformation(1000)
if err != nil {
// Something is wrong. Do something.
}
when you're calling a function to get information from an employee object, you might want to know if the employee exists. Go's opinionated way for handling such an expected error.
Notice how the function returns the employee struct and also an error as a second value. The error could be nil. If the error is nil, that means success. If it's not nil, that means failure. A non-nil error comes with an error message that you can either print or, preferably, log. This is how you handle errors in Go.
Top comments (0)