From ea637fa298c41afc70479b4bcc61ef649ef86118 Mon Sep 17 00:00:00 2001 From: Paul Wells Date: Tue, 19 Nov 2024 17:28:18 -0800 Subject: [PATCH] add utility for reading http status from psrpc error --- rpc/error.go | 29 +++++++++++++++++++++++++++++ rpc/error_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 rpc/error.go create mode 100644 rpc/error_test.go diff --git a/rpc/error.go b/rpc/error.go new file mode 100644 index 00000000..4c69f42b --- /dev/null +++ b/rpc/error.go @@ -0,0 +1,29 @@ +// Copyright 2023 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package rpc + +import ( + "errors" + + "github.com/livekit/psrpc" +) + +func ErrHttpStatus(err error) (int, bool) { + var psrpcErr psrpc.Error + if errors.As(err, &psrpcErr) { + return psrpcErr.ToHttp(), true + } + return 0, false +} diff --git a/rpc/error_test.go b/rpc/error_test.go new file mode 100644 index 00000000..c4c488d0 --- /dev/null +++ b/rpc/error_test.go @@ -0,0 +1,30 @@ +// Copyright 2023 LiveKit, Inc. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package rpc + +import ( + "net/http" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/livekit/psrpc" +) + +func TestErrHttpStatus(t *testing.T) { + code, ok := ErrHttpStatus(psrpc.NewErrorf(psrpc.NotFound, "not found")) + require.True(t, ok) + require.Equal(t, http.StatusNotFound, code) +}