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