mirror of
https://github.com/alrayyes/wiki.git
synced 2024-11-29 14:36:22 +00:00
57 lines
904 B
Markdown
57 lines
904 B
Markdown
|
---
|
||
|
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>
|