Go traps · Chapter 2 of 16

A shadowed err

Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Everyday traps
  • 3 tasks
  • Go
  • Free chapter

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.

Why you need this

Both errs are used, so the compiler is happy, and go vet says nothing. Its shadow checker is not one of the analyzers it runs, and the old flag is gone:

$ go vet -shadow .
flag provided but not defined: -shadow

The usual fix: return the error where it happens, inside the loop, or declare the other variables first and assign with = so there is only one err.

The lesson

By the end of this case

You can spot an err that := quietly replaced inside a block, make a lost error happen on purpose with a fake, fix it, and guard it with a test that checks the error with errors.Is.

The ticket

BG-715: Refund batch says "all paid", the bank paid two. Assigned to you by Joseph. Priority: high. Since: last week's release.

Pooja, in the finance channel at 10:05 am: "Last night's refund batch said all nine refunds were paid. The bank's statement shows two. Seven drivers whose sessions failed yesterday are still waiting for their money, and two have already called. The bank says their side was down for an hour from 2 am."

The refunds job's log from 2 am:

02:00:01  refunds  refund S902114: 18000 paise, ref HDFC6130417
02:00:01  refunds  refund S902131: 7400 paise, ref HDFC6130424
02:00:02  refunds  refund batch: all 9 refunds paid

Joseph: "Last week's release made PayRefunds stop at the first payment the bank refuses, so the batch can be run again for the rest. The log shows two refund lines, then 'all 9 paid': the loop stopped, and nobody was told why. The batch only knows what PayRefunds returns. Reproduce it with a bank that says no, fix it, and make sure a refused payment can never look like success again. You are in refund.go."

:= makes new variables

:= declares the variables on its left in the block where it is written. Inside a loop body or an if, that is a new, inner block, so v, err := f() makes a brand new err that hides (shadows) any err outside. Assignments to it never reach the outer one:

var err error
if true {
	_, err := strconv.Atoi("12OO")
	fmt.Println("inside: ", err)
}
fmt.Println("outside:", err)
inside:  strconv.Atoi: parsing "12OO": invalid syntax
outside: <nil>

Here is a meter total with the same trap. Given the readings "1200", "12OO" (letters, not zeros) and "900", the bad reading stops the loop, and the function still says all is well:

func total(readings []string) (int, error) {
	var err error
	sum := 0
	for _, r := range readings {
		wh, err := strconv.Atoi(r)
		if err != nil {
			break
		}
		sum += wh
	}
	return sum, err
}
1200 <nil>

Making it happen on purpose

The real bank was down for an hour, and you cannot ask it to fail again. But PayRefunds takes a Bank, an interface, so any type with the same method will do. A fake is a small type you write that does exactly what the test needs: pay, refuse, count its calls. A fake SMS sender that fails on a chosen call:

type failingSender struct{ calls, failAt int }

func (s *failingSender) Send(phone, text string) error {
	s.calls++
	if s.calls == s.failAt {
		return errors.New("sms: gateway busy")
	}
	return nil
}

Your repro returns fmt.Sprint(err), so go run . shows "<nil>" beside the bug.

Checking errors in a test

Errors are often wrapped (fmt.Errorf("pay %s: %w", driver, err)), so compare them with errors.Is(err, target), which looks through the wrapping, rather than ==:

func TestTotalBadReading(t *testing.T) {
	_, err := total([]string{"1200", "12OO", "900"})
	if !errors.Is(err, strconv.ErrSyntax) {
		t.Fatalf("got %v, want strconv.ErrSyntax", err)
	}
}
$ go test
--- FAIL: TestTotalBadReading (0.00s)
    total_test.go:12: got <nil>, want strconv.ErrSyntax
FAIL

Your turn

Three tasks, one file each. In repro.go, give PayRefunds a fake bank that refuses the second refund and return what it returned, as text; run it with go run .. In refund.go, fix PayRefunds so the bank's error comes back and nothing after it is paid. In refund_test.go, write the guard: the check runs it beside the bug, the fix, and a wrong fix that prints the error but still returns nil, so check the returned error, and that a bank that pays everything gives nil. Then answer Joseph's interview question at the bottom of the case.

What you build: 3 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    repro.go: lose a refused payment on purpose

    Write reproduce() in repro.go, which returns a string. Write a fake bank, a type with a method Pay(driver string, paise int) (string, error), that pays the first refund (any reference will do) and refuses the second with ErrBankDown. Call PayRefunds with it and two or more refunds, and return fmt.Sprint of the error PayRefunds returned.

    The check runs your reproduce() twice, each time in a fresh build of the case's folder: beside the original refund.go it must return "<nil>" (a refused payment, and no error), and beside a fixed refund.go it must return the error your fake gave, "bank: payments unavailable" for ErrBankDown. So the fake bank must really refuse a payment. No real waiting and no input: reproduce() must finish within 3 seconds.

  2. Task 2

    refund.go: a refused payment stops the batch and says so

    Fix PayRefunds(bank Bank, refunds []Refund) error in refund.go. When the bank refuses a payment, PayRefunds must return that error (errors.Is must find it, so returning it as it is or wrapping it with %w are both fine) and must not ask the bank for any payment after it. When every payment works, and when there are no refunds at all, it must return nil.

    Keep Bank, Refund, ErrBankDown, NightlyRefunds and the line refund <session>: <paise> paise, ref <ref> printed for each paid refund. The check uses its own fake banks, refunds and errors (ErrBankDown wrapped, and an error of its own), so printing the error inside the loop is not enough: the caller only knows what PayRefunds returns.

  3. Task 3

    refund_test.go: a test that would have caught it

    Write a Go test file, refund_test.go, that would have caught this bug before the release. The check runs your file three times, each in a fresh build: beside the original refund.go, where at least one test must fail; beside the fixed refund.go, where every test must pass; and beside a wrong fix that prints the bank's error but still returns nil, where at least one test must fail.

    So test what PayRefunds returns, on both sides: with a bank that refuses a payment, the returned error must be the bank's (check it with errors.Is), and with a bank that pays everything, it must be nil. Your test may use the fake bank from repro.go (the same package); a second fake needs another name. Each test must finish within a second or two (the whole file is stopped after 8 seconds).

What you will learn

  • repro.go: lose a refused payment on purpose
  • refund.go: a refused payment stops the batch and says so
  • refund_test.go: a test that would have caught it

More in Everyday traps

Build "A shadowed err" yourself

BijliGo runs its EV chargers on Go, and Joseph, its senior engineer, keeps assigning you tickets. Each is a real trap interviews love to ask about. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

Free with a Google or GitHub sign-in, like the first 2 chapters of every lab.