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 <jmulligan@redhat.com>
This commit is contained in:
John Mulligan 2020-08-10 11:02:03 -04:00 committed by John Mulligan
parent ab49935b5b
commit 828ea92a51
2 changed files with 19 additions and 12 deletions

View File

@ -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)
}

View File

@ -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")
}