[Awesome Go] Errors handling before Go 1.13 - errors - Programming Language - Golang (Go) - Exception Error Handling
error
In error handling in the Go language, errors are an important part of the software package API and application user interface. Errors are returned as a normal return value.
In this article, we are going to explore error handling before Go 1.13.
error
is a built-in type in Go.
1 | type error interface { |
An idiomatic way to handle an error is to return it as the last return value of a function call and check for the nil condition.
1 | val, err := myFunction( args... ); |
errors.new(string) error
errors.New constructs a basic error value with the given error message.
1 | package main |
Run main.go.
1 | go run main.go |
fmt.Errorf(string, …interface{}) error
The fmt.Errorf() function in Go language allow us use formatting features to create descriptive error messages.
It will format an string and return an error by call errors.new(string)
.
1 | func Errorf(format string, a ...interface{}) error |
Example main.go
1 | // Golang program to illustrate the usage of |
Run main.go.
1 | go run main.go |
Through the fmt.Errorf
function, a new err is generated based on the existing err, and then the text information we want to add is appended. This method is more convenient, but the problem is also obvious, we lost the original err information.
Custom Error
We can customize our own error struct and add fields for storing additional error information we need.
In Go language, any type that implements the error
interface is as an error. So, let’s create our first error by implementing error interface.
Example: main.go
1 | package main |
Run main.go.
1 | go run main.go |
An error value may be of any type which satisfies the language-defined error interface. A program can use a type assertion (interface{}) (error, bool)
or type switch target_type(interface{})
to view an error value as a more specific type.
1 | type NotFoundError struct { |
References
[1] Working with Errors in Go 1.13 - The Go Blog - https://blog.golang.org/go1.13-errors