You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@beam.apache.org by al...@apache.org on 2019/04/24 16:28:52 UTC

[beam] branch master updated: [BEAM-7087] Creating "errors" package internal to Beam Go SDK

This is an automated email from the ASF dual-hosted git repository.

altay pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/beam.git


The following commit(s) were added to refs/heads/master by this push:
     new 5bfa896  [BEAM-7087] Creating "errors" package internal to Beam Go SDK
     new de2d929  Merge pull request #8369 from youngoli/beam7087
5bfa896 is described below

commit 5bfa896dc249dff2bd4038641775ba50aee16e78
Author: Daniel Oliveira <da...@gmail.com>
AuthorDate: Fri Apr 19 17:33:36 2019 -0700

    [BEAM-7087] Creating "errors" package internal to Beam Go SDK
    
    I'm creating a package that prints well formatted errors for Beam. In
    particular this package differentiates between context and error
    messages and allows the top-level error message to be sent any time
    in the chain of errors and still be the first error to display.
---
 sdks/go/pkg/beam/internal/errors.go      | 186 ++++++++++++++++++++++++++++
 sdks/go/pkg/beam/internal/errors_test.go | 203 +++++++++++++++++++++++++++++++
 2 files changed, 389 insertions(+)

diff --git a/sdks/go/pkg/beam/internal/errors.go b/sdks/go/pkg/beam/internal/errors.go
new file mode 100644
index 0000000..0f3d78f
--- /dev/null
+++ b/sdks/go/pkg/beam/internal/errors.go
@@ -0,0 +1,186 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package errors
+
+import (
+	"fmt"
+	"io"
+	"strings"
+)
+
+// New returns an error with the given message.
+func New(message string) error {
+	return fmt.Errorf("%s", message)
+}
+
+// Errorf returns an error with a message formatted according to the format
+// specifier.
+func Errorf(format string, args ...interface{}) error {
+	return fmt.Errorf(format, args...)
+}
+
+// Wrap returns a new error annotating err with a new message.
+func Wrap(err error, message string) error {
+	if err == nil {
+		return nil
+	}
+	return &beamError{
+		cause: err,
+		msg:   message,
+		top:   getTop(err),
+	}
+}
+
+// Wrapf returns a new error annotating err with a new message according to
+// the format specifier.
+func Wrapf(err error, format string, args ...interface{}) error {
+	if err == nil {
+		return nil
+	}
+	return &beamError{
+		cause: err,
+		msg:   fmt.Sprintf(format, args...),
+		top:   getTop(err),
+	}
+}
+
+// WithContext returns a new error adding additional context to err.
+func WithContext(err error, context string) error {
+	if err == nil {
+		return nil
+	}
+	return &beamError{
+		cause:   err,
+		context: context,
+		top:     getTop(err),
+	}
+}
+
+// WithContextf returns a new error adding additional context to err according
+// to the format specifier.
+func WithContextf(err error, format string, args ...interface{}) error {
+	if err == nil {
+		return nil
+	}
+	return &beamError{
+		cause:   err,
+		context: fmt.Sprintf(format, args...),
+		top:     getTop(err),
+	}
+}
+
+// SetTopLevelMsg returns a new error with the given top level message. The top
+// level message is the first error message that gets printed when Error()
+// is called on the returned error or any error wrapping it.
+func SetTopLevelMsg(err error, top string) error {
+	if err == nil {
+		return nil
+	}
+	return &beamError{
+		cause: err,
+		top:   top,
+	}
+}
+
+// SetTopLevelMsgf returns a new error with the given top level message
+// according to the format specifier. The top level message is the first error
+// message that gets printed when Error() is called on the returned error or
+// any error wrapping it.
+func SetTopLevelMsgf(err error, format string, args ...interface{}) error {
+	if err == nil {
+		return nil
+	}
+	return &beamError{
+		cause: err,
+		top:   fmt.Sprintf(format, args...),
+	}
+}
+
+func getTop(e error) string {
+	if be, ok := e.(*beamError); ok {
+		return be.top
+	}
+	return e.Error()
+}
+
+// beamError represents one or more details about an error. They are usually
+// nested in the order that additional context was wrapped around the original
+// error.
+//
+// The presence or lack of certain fields implicitly indicates some details
+// about the error.
+//
+// * If no cause is present it indicates that this instance is the original
+//   error, and the message is assumed to be present.
+// * If both message and context are present, the context describes this error
+//   not the next error.
+// * top is always assumed to be present since it is propogated up from the
+//   original error if not explicitly set.
+type beamError struct {
+	cause   error  // The error being wrapped. If nil then this is the first error.
+	context string // Adds additional context to this error and any following.
+	msg     string // Message describing an error.
+	top     string // The first error message to display to a user. Propogated upwards.
+}
+
+// Error outputs a beamError as a string. The top-level error message is
+// displayed first, followed by each error's context and error message in
+// sequence. The original error is output last.
+func (e *beamError) Error() string {
+	var builder strings.Builder
+
+	if e.top != "" {
+		builder.WriteString(fmt.Sprintf("%s\nFull error:\n", e.top))
+	}
+
+	e.printRecursive(&builder)
+
+	return builder.String()
+}
+
+// printRecursive outputs the contexts and messages of beamErrors recursively
+// while ignoring the top-level error. This avoids calling Error recursively on
+// beamErrors since that would repeatedly print top-level messages.
+func (e *beamError) printRecursive(builder *strings.Builder) {
+	wraps := e.cause != nil
+
+	if e.context != "" {
+		builder.WriteString(fmt.Sprintf("\t%s:\n", e.context))
+	}
+	if e.msg != "" {
+		builder.WriteString(e.msg)
+		if wraps {
+			builder.WriteString("\nCaused by:\n")
+		}
+	}
+
+	if wraps {
+		if be, ok := e.cause.(*beamError); ok {
+			be.printRecursive(builder)
+		} else {
+			builder.WriteString(e.cause.Error())
+		}
+	}
+}
+
+func (e *beamError) Format(s fmt.State, verb rune) {
+	switch verb {
+	case 'v', 's':
+		io.WriteString(s, e.Error())
+	case 'q':
+		fmt.Fprintf(s, "%q", e.Error())
+	}
+}
diff --git a/sdks/go/pkg/beam/internal/errors_test.go b/sdks/go/pkg/beam/internal/errors_test.go
new file mode 100644
index 0000000..5df0da0
--- /dev/null
+++ b/sdks/go/pkg/beam/internal/errors_test.go
@@ -0,0 +1,203 @@
+// Licensed to the Apache Software Foundation (ASF) under one or more
+// contributor license agreements.  See the NOTICE file distributed with
+// this work for additional information regarding copyright ownership.
+// The ASF licenses this file to You under the Apache License, Version 2.0
+// (the "License"); you may not use this file except in compliance with
+// the License.  You may obtain a copy of the License at
+//
+//    http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package errors
+
+import (
+	"fmt"
+	"testing"
+)
+
+func TestNew(t *testing.T) {
+	const want string = "error message"
+	err := New(want)
+	if err.Error() != want {
+		t.Errorf("Error msg does not match original. Want: %q, Got: %q", want, err.Error())
+	}
+}
+
+func TestErrorf(t *testing.T) {
+	want := fmt.Sprintf("%s %d", "ten", 10)
+	err := Errorf("%s %d", "ten", 10)
+	if err.Error() != want {
+		t.Errorf("Incorrect formatting. Want: %q, Got: %q", want, err.Error())
+	}
+}
+
+const (
+	base string = "base"
+	msg1 string = "message 1"
+	msg2 string = "message 2"
+	ctx1 string = "context 1"
+	ctx2 string = "context 2"
+	top1 string = "top level message 1"
+	top2 string = "top level message 2"
+)
+
+func TestWrap(t *testing.T) {
+	tests := []struct {
+		err  error
+		want errorStructure
+	}{
+		{
+			err:  Wrap(New(base), msg1),
+			want: errorStructure{{ERROR, msg1}, {ERROR, base}},
+		}, {
+			err:  Wrap(Wrap(New(base), msg1), msg2),
+			want: errorStructure{{ERROR, msg2}, {ERROR, msg1}, {ERROR, base}},
+		},
+	}
+	for _, test := range tests {
+		got := getStructure(test.err)
+		if !equalStructure(got, test.want) {
+			t.Errorf("Incorrect structure. Want: %+v, Got: %+v", test.want, got)
+		}
+	}
+}
+
+func TestWrapf(t *testing.T) {
+	want := fmt.Sprintf("%s %d", "ten", 10)
+	err := Wrapf(New(base), "%s %d", "ten", 10)
+	got := getStructure(err)[0].msg
+	if got != want {
+		t.Errorf("Incorrect formatting. Want: %q, Got: %q", want, got)
+	}
+}
+
+func TestContext(t *testing.T) {
+	tests := []struct {
+		err  error
+		want errorStructure
+	}{
+		{
+			err:  WithContext(New(base), ctx1),
+			want: errorStructure{{CONTEXT, ctx1}, {ERROR, base}},
+		}, {
+			err:  WithContext(Wrap(WithContext(New(base), ctx1), msg1), ctx2),
+			want: errorStructure{{CONTEXT, ctx2}, {ERROR, msg1}, {CONTEXT, ctx1}, {ERROR, base}},
+		}, {
+			err:  Wrap(WithContext(WithContext(Wrap(New(base), msg1), ctx1), ctx2), msg2),
+			want: errorStructure{{ERROR, msg2}, {CONTEXT, ctx2}, {CONTEXT, ctx1}, {ERROR, msg1}, {ERROR, base}},
+		},
+	}
+	for _, test := range tests {
+		got := getStructure(test.err)
+		if !equalStructure(got, test.want) {
+			t.Errorf("Incorrect structure. Want: %+v, Got: %+v", test.want, got)
+		}
+	}
+}
+
+func TestWithContextf(t *testing.T) {
+	want := fmt.Sprintf("%s %d", "ten", 10)
+	err := WithContextf(New(base), "%s %d", "ten", 10)
+	got := getStructure(err)[0].msg
+	if got != want {
+		t.Errorf("Incorrect formatting. Want: %q, Got: %q", want, got)
+	}
+}
+
+func TestTopLevelMsg(t *testing.T) {
+	tests := []struct {
+		err  error
+		want string
+	}{
+		{
+			err:  New(base),
+			want: base,
+		}, {
+			err:  Wrap(WithContext(New(base), ctx1), msg1),
+			want: base,
+		}, {
+			err:  SetTopLevelMsg(New(base), top1),
+			want: top1,
+		}, {
+			err:  Wrap(SetTopLevelMsg(WithContext(New(base), ctx1), top1), msg1),
+			want: top1,
+		}, {
+			err:  Wrap(SetTopLevelMsg(WithContext(SetTopLevelMsg(New(base), top1), ctx1), top2), msg1),
+			want: top2,
+		},
+	}
+	for _, test := range tests {
+		got := getTop(test.err)
+		if got != test.want {
+			t.Errorf("Incorrect top-level message. Want: %+v, Got: %+v", test.want, got)
+		}
+	}
+}
+
+func TestSetTopLevelMsgf(t *testing.T) {
+	want := fmt.Sprintf("%s %d", "ten", 10)
+	err := SetTopLevelMsgf(New(base), "%s %d", "ten", 10)
+	if getTop(err) != want {
+		t.Errorf("Incorrect formatting. Want: %q, Got: %q", want, getTop(err))
+	}
+}
+
+// getStructure extracts the structure of an error, outputting a slice that
+// represents the nested messages in that error in the order they are output
+// and with the type of message (context or error) described.
+func getStructure(e error) errorStructure {
+	var structure errorStructure
+
+	for {
+		if be, ok := e.(*beamError); ok {
+			if be.context != "" {
+				structure = append(structure, entry{CONTEXT, be.context})
+			}
+			if be.msg != "" {
+				structure = append(structure, entry{ERROR, be.msg})
+			}
+			// Continue by iterating into the cause of the error.
+			if be.cause != nil {
+				e = be.cause
+			} else {
+				return structure
+			}
+		} else { // Not a beamError.
+			structure = append(structure, entry{ERROR, e.Error()})
+			return structure
+		}
+	}
+}
+
+func equalStructure(left errorStructure, right errorStructure) bool {
+	if len(left) != len(right) {
+		return false
+	}
+
+	for i := 0; i < len(left); i++ {
+		if left[i].t != right[i].t || left[i].msg != right[i].msg {
+			return false
+		}
+	}
+
+	return true
+}
+
+type msgType int
+
+const (
+	ERROR msgType = iota
+	CONTEXT
+)
+
+type entry struct {
+	t   msgType
+	msg string
+}
+
+type errorStructure []entry