Skip to content

Commit

Permalink
wasi: support converting more errors to wasi.Errno (#73)
Browse files Browse the repository at this point in the history
Signed-off-by: Achille Roussel <[email protected]>
  • Loading branch information
achille-roussel authored Jun 27, 2023
1 parent 341ced8 commit ba8560e
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
33 changes: 33 additions & 0 deletions error_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
package wasi_test

import (
"context"
"fmt"
"io"
"io/fs"
"net"
"os"
"syscall"
"testing"

"github.com/stealthrocket/wasi-go"
Expand All @@ -17,3 +24,29 @@ func TestErrno(t *testing.T) {
})
}
}

func TestMakeErrno(t *testing.T) {
tests := []struct {
error error
errno wasi.Errno
}{
{nil, wasi.ESUCCESS},
{syscall.EAGAIN, wasi.EAGAIN},
{context.Canceled, wasi.ECANCELED},
{context.DeadlineExceeded, wasi.ETIMEDOUT},
{io.ErrUnexpectedEOF, wasi.EIO},
{fs.ErrClosed, wasi.EIO},
{net.ErrClosed, wasi.EIO},
{syscall.EPERM, wasi.EPERM},
{wasi.EAGAIN, wasi.EAGAIN},
{os.ErrDeadlineExceeded, wasi.ETIMEDOUT},
}

for _, test := range tests {
t.Run(fmt.Sprint(test.error), func(t *testing.T) {
if errno := wasi.MakeErrno(test.error); errno != test.errno {
t.Errorf("error mismatch: want=%d got=%d (%s)", test.errno, errno, errno)
}
})
}
}
20 changes: 19 additions & 1 deletion error_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"net"
"syscall"
)

Expand All @@ -18,22 +21,37 @@ func makeErrno(err error) Errno {
}

func makeErrnoSlow(err error) Errno {
if err == context.Canceled {
switch {
case errors.Is(err, context.Canceled):
return ECANCELED
case errors.Is(err, context.DeadlineExceeded):
return ETIMEDOUT
case errors.Is(err, io.ErrUnexpectedEOF),
errors.Is(err, fs.ErrClosed),
errors.Is(err, net.ErrClosed):
return EIO
}

var sysErrno syscall.Errno
if errors.As(err, &sysErrno) {
if sysErrno == 0 {
return ESUCCESS
}
return syscallErrnoToWASI(sysErrno)
}

var wasiErrno Errno
if errors.As(err, &wasiErrno) {
return wasiErrno
}

var timeout interface{ Timeout() bool }
if errors.As(err, &timeout) {
if timeout.Timeout() {
return ETIMEDOUT
}
}

panic(fmt.Errorf("unexpected error: %v", err))
}

Expand Down

0 comments on commit ba8560e

Please sign in to comment.