frankban / frankban/quicktest

proposal: add Try and Recover

Open
#138 8 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
527
Forks
28
PR merge metrics
No merged PRs in 30d

Description

Error handling is tedious, and when writing tests we are prioritizing getting the test written quickly rather than necessarily making it the most robust piece of code we ever wrote.

I propose adding the following:
```go
func (c *C) Recover()
func Try(error)
func Try1[A any](A, error) A
func Try2[A, B any](A, B, error) (A, B)
func Try3[A, B, C any](A, B, C, error) (A, B, C)
func Try4[A, B, C, D any](A, B, C, D, error) (A, B, C, D)
```
where the `Try` functions panic if `err` is non-nil. Otherwise, it peels off the `error` and returns the other arguments as is.
The `TryN` functions are defined such that `N` is the number of return arguments. Generics in Go do not have variadic parametric types, so we cannot express a generic function with a generic number of arguments. `Try4` should be sufficient since no standard library function has more than 4 return arguments.

Example usage:
```go
func Test(t *testing.T) {
c := qt.New(t)
defer c.Recover() // catch errors panicked by calls to `Try` below

zr := qt.Try1(gzip.NewReader(...))
b := qt.Try1(io.ReadAll(zr))
... = b
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.