errutil: common error handling functions

Signed-off-by: John Mulligan <jmulligan@redhat.com>
This commit is contained in:
John Mulligan 2019-12-12 13:20:45 -05:00 committed by Niels de Vos
parent f15486e0a2
commit 887dec1c50
2 changed files with 73 additions and 0 deletions

41
errutil/strerror.go Normal file
View File

@ -0,0 +1,41 @@
package errutil
/* force XSI-complaint strerror_r() */
// #define _POSIX_C_SOURCE 200112L
// #undef _GNU_SOURCE
// #include <stdlib.h>
// #include <errno.h>
// #include <string.h>
import "C"
import (
"unsafe"
)
// FormatErrno returns the absolute value of the errno as well as a string
// describing the errno. The string will be empty is the errno is not known.
func FormatErrno(errno int) (int, string) {
buf := make([]byte, 1024)
// strerror expects errno >= 0
if errno < 0 {
errno = -errno
}
ret := C.strerror_r(
C.int(errno),
(*C.char)(unsafe.Pointer(&buf[0])),
C.size_t(len(buf)))
if ret != 0 {
return errno, ""
}
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
}

32
errutil/strerror_test.go Normal file
View File

@ -0,0 +1,32 @@
package errutil
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestFormatError(t *testing.T) {
e, msg := FormatErrno(39)
assert.Equal(t, 39, e)
assert.Equal(t, msg, "Directory not empty")
e, msg = FormatErrno(-5)
assert.Equal(t, 5, e)
assert.Equal(t, msg, "Input/output error")
e, msg = FormatErrno(345)
assert.Equal(t, 345, e)
assert.Equal(t, msg, "")
}
func TestStrError(t *testing.T) {
msg := StrError(39)
assert.Equal(t, msg, "Directory not empty")
msg = StrError(-5)
assert.Equal(t, msg, "Input/output error")
msg = StrError(345)
assert.Equal(t, msg, "")
}