Notice how we say errors and not exceptions - there is no exception handling in Go.
error type which is an interface type:
Divide function which divides integer a by b:
Constructing Errors
There are multiple ways to construct errors, but we will look at the two most common ones.errors package
The first is by using the New function provided by the errors package:
Notice how we return an
error with the result. If there is no error we simply return nil as it is the zero value of an error (since it’s an interface).main function:
nil and build our logic accordingly. This is considered quite idiomatic in Go.
fmt.Errorf
Another way to construct errors is by using the fmt.Errorf function.
This function is similar to fmt.Sprintf and lets us format our error. But instead of returning a string, it returns an error. It is often used to add context or detail to our errors:
Sentinel Errors
Another important technique in Go is defining expected errors so they can be checked explicitly in other parts of the code. These are sometimes referred to as sentinel errors.In Go, it is conventional to prefix the variable with
Err. For example, ErrNotFound.Why use sentinel errors?
This becomes useful when we need to execute a different branch of code if a certain kind of error is encountered. We can check explicitly which error occurred using theerrors.Is function:
Custom Errors
This strategy covers most error handling use cases. But sometimes we need additional functionalities such as dynamic values inside our errors. We saw thaterror is just an interface. Basically, anything can be an error as long as it implements the Error() method which returns an error message as a string.
Let’s define a custom DivisionError struct:
errors.As instead of errors.Is to convert the error to the correct type:
Difference between errors.Is and errors.As
The
errors.As function checks whether the error has a specific type, while errors.Is examines if it is a particular error object.Error handling in Go is quite different compared to the traditional
try/catch idiom in other languages. But it is very powerful as it encourages developers to actually handle the error in an explicit way, which improves readability.