wiki/content/20200909202454-errors.md

58 lines
921 B
Markdown
Raw Normal View History

2024-05-06 20:40:05 +00:00
---
2024-10-29 18:27:12 +00:00
date: 2020-09-09
2024-05-06 20:40:05 +00:00
id: 5114b51a-da22-4c9c-a12c-c416aeb984b6
title: Golang Errors
---
# Basics
Go supports Errors
``` go
import (
"errors"
"fmt"
)
func ThrowError(throwError bool) error {
if throwError {
return errors.New("This is an error")
}
fmt.Println("No error was thrown!")
return nil
}
func main() {
ThrowError(true)
ThrowError(false)
}
```
# Wrappers
It appears to be good practice to make errors a `const`. This example
uses the Error [interface](20200831171822-interfaces):
``` go
const (
ErrNotFound = DictionaryErr("could not find the word you were looking for")
ErrWordExists = DictionaryErr("cannot add word because it already exists")
)
type DictionaryErr string
func (e DictionaryErr) Error() string {
return string(e)
}
```
# Handy Links
- Constant errors[^1]
# Footnotes
[^1]: <https://dave.cheney.net/2016/04/07/constant-errors>