Skip to content

Commit

Permalink
Handle not exception errors from the server
Browse files Browse the repository at this point in the history
  • Loading branch information
avillen committed Jun 14, 2023
1 parent 3cbd100 commit 5330612
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/grpc/server/adapters/cowboy/handler.ex
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,12 @@ defmodule GRPC.Server.Adapters.Cowboy.Handler do
result = server.__call_rpc__(path, stream)

case result do
{:ok, _stream, error = %GRPC.RPCError{message: nil, status: status}} ->
{:error, %{error | message: GRPC.Status.status_message(status)}}

{:ok, _stream, error = %GRPC.RPCError{}} ->
{:error, error}

{:ok, stream, response} ->
stream
|> GRPC.Server.send_reply(response)
Expand Down
40 changes: 40 additions & 0 deletions test/grpc/integration/server_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,19 @@ defmodule GRPC.Integration.ServerTest do
raise "unknown error(This is a test, please ignore it)"
end

def say_hello(%{name: "handled error"}, _stream) do
%GRPC.RPCError{
status: GRPC.Status.unauthenticated(),
message: "Please authenticate"
}
end

def say_hello(%{name: "handled error without message"}, _stream) do
%GRPC.RPCError{
status: GRPC.Status.unauthenticated()
}
end

def say_hello(_req, _stream) do
raise GRPC.RPCError, status: GRPC.Status.unauthenticated(), message: "Please authenticate"
end
Expand Down Expand Up @@ -172,6 +185,33 @@ defmodule GRPC.Integration.ServerTest do
end)
end

test "return errors for handled errors" do
run_server([HelloErrorServer], fn port ->
{:ok, channel} = GRPC.Stub.connect("localhost:#{port}")
req = Helloworld.HelloRequest.new(name: "handled error")
{:error, reply} = channel |> Helloworld.Greeter.Stub.say_hello(req)

assert %GRPC.RPCError{
status: GRPC.Status.unauthenticated(),
message: "Please authenticate"
} == reply
end)
end

test "return errors for handled errors with the default message of the status" do
run_server([HelloErrorServer], fn port ->
{:ok, channel} = GRPC.Stub.connect("localhost:#{port}")
req = Helloworld.HelloRequest.new(name: "handled error without message")
{:error, reply} = channel |> Helloworld.Greeter.Stub.say_hello(req)

assert %GRPC.RPCError{
status: GRPC.Status.unauthenticated(),
message:
"The request does not have valid authentication credentials for the operation"
} == reply
end)
end

test "returns appropriate error for stream requests" do
run_server([FeatureErrorServer], fn port ->
{:ok, channel} = GRPC.Stub.connect("localhost:#{port}")
Expand Down

0 comments on commit 5330612

Please sign in to comment.