Error handling case analysis in the Go language
- 2020-05-26 09:17:39
- OfStack
This article demonstrates an example of error handling in the Go language. Share with you for your reference. The specific analysis is as follows:
The error is to be able to describe anything in a string. The main idea is to consist of a predefined built-in interface type, error, and its method, Error, which returns the return string.
type error interface {
Error() string
}
This method is automatically called when an error is printed using the various printing functions of the fmt package.
package main
import (
"fmt"
"time"
)
type MyError struct {
When time.Time
What string
}
func (e *MyError) Error() string {
return fmt.Sprintf("at %v, %s",
e.When, e.What)
}
func run() error {
return &MyError{
time.Now(),
"it didn't work",
}
}
func main() {
if err := run(); err != nil {
fmt.Println(err)
}
}
I hope this article has helped you with your Go language programming.