|
Packit |
63bb0d |
# Error Handling
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
## When to Panic
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
Always use `panic` for errors that can only happen when other code in
|
|
Packit |
63bb0d |
*osbuild-composer* is wrong (also know as *programmer error*). This way, we
|
|
Packit |
63bb0d |
catch these kinds of errors in unit tests while developing.
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
Since only developers interact with these errors, a stacktrace including the
|
|
Packit |
63bb0d |
error is all that's necessary. Don't include an additional message.
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
For example, Go's `json.Marshal` can fail when receiving values that cannot be
|
|
Packit |
63bb0d |
marshaled. However, when passing a known struct, we know it cannot fail:
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
```golang
|
|
Packit |
63bb0d |
bytes, err := json.Marshal();
|
|
Packit |
63bb0d |
if err != nil {
|
|
Packit |
63bb0d |
panic(err)
|
|
Packit |
63bb0d |
}
|
|
Packit |
63bb0d |
```
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
Some packages have functions prefixed with `Must`, which `panic()` on error.
|
|
Packit |
63bb0d |
Use these when possible to save the error check:
|
|
Packit |
63bb0d |
|
|
Packit |
63bb0d |
```golang
|
|
Packit |
63bb0d |
re := regexp.MustCompile("v[0-9]")
|
|
Packit |
63bb0d |
```
|