The error interface
- Go course
- Beginner
- Lesson 83/90
- 4 min
Learn the error interface and the Error() method.
The error interface
In Go an error is any value that satisfies the built-in error interface:
type error interface {
Error() string
}Functions return the error as their last value; on success they return nil. Errors aren't exceptions but ordinary values; they are checked with if err != nil.
f, err := os.Open("ayar.json")
if err != nil {
return err
}
defer f.Close()A custom error type
Error types that carry extra information let the caller handle the error better:
type DogrulamaHatasi struct {
Alan string
Neden string
}
func (e *DogrulamaHatasi) Error() string {
return e.Alan + ": " + e.Neden
}
func dogrula(yas int) error {
if yas < 0 {
return &DogrulamaHatasi{"yaş", "negatif olamaz"}
}
return nil
}Practice Validation error
Write the DogrulamaHatasi type and the dogrula(yas int) error function above. Print the results of dogrula(-3) and dogrula(20) on separate lines.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
type DogrulamaHatasi struct {
Alan string
Neden string
}
func (e *DogrulamaHatasi) Error() string {
return e.Alan + ": " + e.Neden
}
func dogrula(yas int) error {
if yas < 0 {
return &DogrulamaHatasi{"yaş", "negatif olamaz"}
}
return nil
}
func main() {
fmt.Println(dogrula(-3))
fmt.Println(dogrula(20))
}Expected output
yaş: negatif olamaz <nil>
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is needed to write your own error type?
- Calling panic
- Registering with the errors package
- A type with an Error() string method Correct answer
- Inheriting from error
Explanation: Implicit satisfaction applies here too; any type with an Error() string method is an error.
2 Error method
func (e *DogrulamaHatasi) ____() string {
return e.Alan + ": " + e.Neden
}
func (e *DogrulamaHatasi) Error() string {
return e.Alan + ": " + e.Neden
}
Explanation: The Error() string method makes the type satisfy the error interface.
3 Concept
| Term | Meaning |
|---|---|
error |
Error() string |
A nil error |
Success |
if err != nil |
Error check |
*DogrulamaHatasi |
Custom error type |