From 9a0e9f18c6e22f6b32f439065e844bcdd2d1892c Mon Sep 17 00:00:00 2001 From: TAV2BJ Date: Thu, 2 Nov 2023 13:10:18 +0100 Subject: [PATCH] Gets error code from error as int --- client_test.go | 4 ++++ errors.go | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/client_test.go b/client_test.go index 65724fb..78bac22 100644 --- a/client_test.go +++ b/client_test.go @@ -327,6 +327,7 @@ func TestReadStreamRangeUnkownLength(t *testing.T) { func TestStat(t *testing.T) { cli, srv, _, _ := newServer(t) defer srv.Close() + wantErrCode := 404 info, err := cli.Stat("/hello.txt") if err != nil { @@ -343,6 +344,9 @@ func TestStat(t *testing.T) { if !IsErrNotFound(err) { t.Fatalf("got: %v, want 404 error", err) } + if GetStatusCode(err) != wantErrCode { + t.Fatalf("got: %v, want %d", err, wantErrCode) + } } func TestMkdir(t *testing.T) { diff --git a/errors.go b/errors.go index afc1af6..6616a5b 100644 --- a/errors.go +++ b/errors.go @@ -3,6 +3,7 @@ package gowebdav import ( "errors" "fmt" + "net/http" "os" ) @@ -55,3 +56,16 @@ func NewPathErrorErr(op string, path string, err error) error { Err: err, } } + +// GetStatusCode returns status code of the error +func GetStatusCode(err error) int { + var pe *os.PathError + if !errors.As(err, &pe) { + return http.StatusInternalServerError + } + var se StatusError + if !errors.As(pe.Err, &se) { + return http.StatusInternalServerError + } + return se.Status +}