Introduction
GO is an Open Source programming language also known as Golang or GO language. It was developed by Google Engineers. errors.New and fmt.Errorf are the two methods used in GO to generate errors. These two methods are not sufficient to capture or report what exactly happened in the program. To tackle this and get more functionalities we can implement the standard library interface, error.
Syntax:
type error interface {
Error() string
}
This error interface contains a single Error() method which returns the message of an error in the form of a String. By implementing this method we can generate an error of our own type.
Example:
package main
import (
"fmt"
"os"
)
type MyError struct{}
func (m *MyError) Error() string {
return "boom"
}
func sayHello() (string, error) {
return "", &MyError{}
}
func main() {
s, err := sayHello()
if err != nil {
fmt.Println("unexpected error: err:", err)
os.Exit(1)
}
fmt.Println("The string:", s)
}
Output:
unexpected error: err: boom
exit status 1
Collecting Detailed Information in a Custom Error
Mostly, custom errors are the best way to generate detailed information about the errors in the programs.
Let us understand this with an example. We will try to capture the status code of the error produced by an HTTP request.
Example:
package main
import (
"errors"
"fmt"
"os"
)
type RequestError struct {
StatusCode int
Err error
}
func (r *RequestError) Error() string {
return fmt.Sprintf("status %d: err %v", r.StatusCode, r.Err)
}
func doRequest() error {
return &RequestError{
StatusCode: 503,
Err: errors.New("unavailable"),
}
}
func main() {
err := doRequest()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println("success!")
}
Output:
status 503: err unavailable
exit status 1
We created a new instance of the RequestError struct. We provided the status code and the error to this instance using the errors.New function. Then using the fmt.Println, we printed the error as done in the previous example.
In the Error() function of the RequestError struct, we have used the fmt.Sprintf() function to construct a string using the information provided when the error was created.