Avatar of exklamationmark

exklamationmark's solution

to Error Handling in the Go Track

Published at Aug 25 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This exercise has changed since this solution was written.

Implement various kinds of error handling and resource management.

An important point of programming is how to handle errors and close resources even if errors occur.

If you are new to Go errors or panics we recommend reading the documentation on these topics first for context.

In this exercise you will be required to define a function Use(o ResourceOpener, input string) error that opens a resource, calls Frob(input) on the result resource and then closes that resource (in all cases). Your function should properly handle errors and panics.

ResourceOpener o will be a function you may invoke directly o() in an attempt to "open" the resource. It returns a Resource and error value in the idiomatic Go fashion:

See the common.go file for the definitions of Resource, ResourceOpener, FrobError and TransientError. You will define your solution to be in the same package as common.go and error_handling_test.go: "erratum". This will make those types available for use in your solution.

There will be a few places in your Use function where errors may occur:

  • Invoking the ResourceOpener function passed into Use as the first parameter, it may fail with an error of type TransientError, if so keep trying to open the resource. If it is some other sort of error, return it from your Use function.

  • Calling the Frob function on the Resource returned from the ResourceOpener function, it may panic with a FrobError (or another type of error). If it is indeed a FrobError you will have to call the Resource's Defrob function using the panic FrobError's .defrobTag variable as input to the Defrob function. Either way Use should return the error.

  • Also note: if the Resource was opened successfully make sure to call its Close function no matter what (even if errors have occurred).

Testing for specific error types may be performed by type assertions. You may also need to look at named return values as a helpful way to return error information from panic recovery.

Running the tests

To run the tests run the command go test from within the exercise directory.

If the test suite contains benchmarks, you can run these with the --bench and --benchmem flags:

go test -v --bench . --benchmem

Keep in mind that each reviewer will run benchmarks on a different machine, with different specs, so the results from these benchmark tests may vary.

Further information

For more detailed information about the Go track, including how to get help if you're having trouble, please visit the exercism.io Go language page.

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

error_handling_test.go

package erratum

import (
	"errors"
	"testing"
)

// Please review the README for this exercise carefully before implementation.

// Little helper to let us customize behaviour of the resource on a per-test
// basis.
type mockResource struct {
	close  func() error
	frob   func(string)
	defrob func(string)
}

func (mr mockResource) Close() error      { return mr.close() }
func (mr mockResource) Frob(input string) { mr.frob(input) }
func (mr mockResource) Defrob(tag string) { mr.defrob(tag) }

// Use should not return an error on the "happy" path.
func TestNoErrors(t *testing.T) {
	var frobInput string
	var closeCalled bool
	mr := mockResource{
		close: func() error { closeCalled = true; return nil },
		frob:  func(input string) { frobInput = input },
	}
	opener := func() (Resource, error) { return mr, nil }
	inp := "hello"
	err := Use(opener, inp)
	if err != nil {
		t.Fatalf("Unexpected error from Use: %v", err)
	}
	if frobInput != inp {
		t.Fatalf("Wrong string passed to Frob: got %v, expected %v", frobInput, inp)
	}
	if !closeCalled {
		t.Fatalf("Close was not called")
	}
}

// Use should keep trying if a transient error is returned on open.
func TestKeepTryOpenOnTransient(t *testing.T) {
	var frobInput string
	mr := mockResource{
		close: func() error { return nil },
		frob:  func(input string) { frobInput = input },
	}
	nthCall := 0
	opener := func() (Resource, error) {
		if nthCall < 3 {
			nthCall++
			return mockResource{}, TransientError{errors.New("some error")}
		}
		return mr, nil
	}
	inp := "hello"
	err := Use(opener, inp)
	if err != nil {
		t.Fatalf("Unexpected error from Use: %v", err)
	}
	if frobInput != inp {
		t.Fatalf("Wrong string passed to Frob: got %v, expected %v", frobInput, inp)
	}
}

// Use should fail if a non-transient error is returned on open.
func TestFailOpenOnNonTransient(t *testing.T) {
	nthCall := 0
	opener := func() (Resource, error) {
		if nthCall < 3 {
			nthCall++
			return mockResource{}, TransientError{errors.New("some error")}
		}
		return nil, errors.New("too awesome")
	}
	inp := "hello"
	err := Use(opener, inp)
	if err == nil {
		t.Fatalf("Unexpected lack of error from Use")
	}
	if err.Error() != "too awesome" {
		t.Fatalf("Invalid error returned from Use")
	}
}

// Use should call Defrob and Close on FrobError panic from Frob
// and return the error.
func TestCallDefrobAndCloseOnFrobError(t *testing.T) {
	tag := "moo"
	var closeCalled bool
	var defrobTag string
	mr := mockResource{
		close: func() error { closeCalled = true; return nil },
		frob:  func(input string) { panic(FrobError{tag, errors.New("meh")}) },
		defrob: func(tag string) {
			if closeCalled {
				t.Fatalf("Close was called before Defrob")
			}
			defrobTag = tag
		},
	}
	opener := func() (Resource, error) { return mr, nil }
	inp := "hello"
	err := Use(opener, inp)
	if err == nil {
		t.Fatalf("Unexpected lack of error from Use")
	}
	if err.Error() != "meh" {
		t.Fatalf("Invalid error returned from Use")
	}
	if defrobTag != tag {
		t.Fatalf("Wrong string passed to Defrob: got %v, expected %v", defrobTag, tag)
	}
	if !closeCalled {
		t.Fatalf("Close was not called")
	}
}

// Use should call Close but not Defrob on non-FrobError panic from Frob
// and return the error.
func TestCallCloseNonOnFrobError(t *testing.T) {
	var closeCalled bool
	var defrobCalled bool
	mr := mockResource{
		close:  func() error { closeCalled = true; return nil },
		frob:   func(input string) { panic(errors.New("meh")) },
		defrob: func(tag string) { defrobCalled = true },
	}
	opener := func() (Resource, error) { return mr, nil }
	inp := "hello"
	err := Use(opener, inp)
	if err == nil {
		t.Fatalf("Unexpected lack of error from Use")
	}
	if err.Error() != "meh" {
		t.Fatalf("Invalid error returned from Use")
	}
	if defrobCalled {
		t.Fatalf("Defrob was called")
	}
	if !closeCalled {
		t.Fatalf("Close was not called")
	}
}
package erratum

func Use(opener ResourceOpener, input string) (err error) {
	var res Resource
	res, err = opener()
	for err != nil {
		switch err.(type) {
		default:
			return err
		case TransientError:
			res, err = opener()
		}
	}

	defer func() {
		if r := recover(); r != nil {
			switch er := r.(type) {
			default:
				panic(er)
			case FrobError:
				res.Defrob(er.defrobTag)
				res.Close()
				err = er
			case error:
				res.Close()
				err = er
			}
			return
		}
		res.Close()
	}()

	res.Frob(input)
	return nil
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?