From 828ea92a51aab305953b535853b1a324d9faf854 Mon Sep 17 00:00:00 2001 From: John Mulligan Date: Mon, 10 Aug 2020 11:02:03 -0400 Subject: [PATCH] errutil: replace unused StrError with FormatErrorCode function This change removes StrError, as it was unused. Instead we add FormatErrorCode which should replace the common code that was previously repeated for all error-code types, along with consistently printing the raw error code value's sign (minus sign when negative). Signed-off-by: John Mulligan --- internal/errutil/strerror.go | 17 ++++++++++++----- internal/errutil/strerror_test.go | 14 +++++++------- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/internal/errutil/strerror.go b/internal/errutil/strerror.go index 907c702..2fb24cb 100644 --- a/internal/errutil/strerror.go +++ b/internal/errutil/strerror.go @@ -14,6 +14,7 @@ package errutil import "C" import ( + "fmt" "unsafe" ) @@ -37,9 +38,15 @@ func FormatErrno(errno int) (int, string) { return errno, C.GoString((*C.char)(unsafe.Pointer(&buf[0]))) } -// StrError returns a string describing the errno. The string will be empty if -// the errno is not known. -func StrError(errno int) string { - _, s := FormatErrno(errno) - return s +// FormatErrorCode returns a string that describes the supplied error source +// and error code as a string. Suitable to use in Error() methods. If the +// error code maps to an errno the string will contain a description of the +// error. Otherwise the string will only indicate the source and value if the +// value does not map to a known errno. +func FormatErrorCode(source string, errValue int) string { + _, s := FormatErrno(errValue) + if s == "" { + return fmt.Sprintf("%s: ret=%d", source, errValue) + } + return fmt.Sprintf("%s: ret=%d, %s", source, errValue, s) } diff --git a/internal/errutil/strerror_test.go b/internal/errutil/strerror_test.go index b89e489..4d17b6c 100644 --- a/internal/errutil/strerror_test.go +++ b/internal/errutil/strerror_test.go @@ -20,13 +20,13 @@ func TestFormatError(t *testing.T) { assert.Equal(t, msg, "") } -func TestStrError(t *testing.T) { - msg := StrError(39) - assert.Equal(t, msg, "Directory not empty") +func TestFormatErrorCode(t *testing.T) { + msg := FormatErrorCode("test", -39) + assert.Equal(t, msg, "test: ret=-39, Directory not empty") - msg = StrError(-5) - assert.Equal(t, msg, "Input/output error") + msg = FormatErrorCode("test", -5) + assert.Equal(t, msg, "test: ret=-5, Input/output error") - msg = StrError(345) - assert.Equal(t, msg, "") + msg = FormatErrorCode("boop", 345) + assert.Equal(t, msg, "boop: ret=345") }