Skip to content

Commit d6706ec

Browse files
committed
Handle not exception errors from the server
1 parent 3cbd100 commit d6706ec

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

lib/grpc/server/adapters/cowboy/handler.ex

+6
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,12 @@ defmodule GRPC.Server.Adapters.Cowboy.Handler do
376376
result = server.__call_rpc__(path, stream)
377377

378378
case result do
379+
{:ok, _stream, error = %GRPC.RPCError{message: nil, status: status}} ->
380+
{:error, %{error | message: GRPC.Status.status_message(status)}}
381+
382+
{:ok, _stream, error = %GRPC.RPCError{}} ->
383+
{:error, error}
384+
379385
{:ok, stream, response} ->
380386
stream
381387
|> GRPC.Server.send_reply(response)

test/grpc/integration/server_test.exs

+39
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,19 @@ defmodule GRPC.Integration.ServerTest do
6060
raise "unknown error(This is a test, please ignore it)"
6161
end
6262

63+
def say_hello(%{name: "handled error"}, _stream) do
64+
%GRPC.RPCError{
65+
status: GRPC.Status.unauthenticated(),
66+
message: "Please authenticate"
67+
}
68+
end
69+
70+
def say_hello(%{name: "handled error without message"}, _stream) do
71+
%GRPC.RPCError{
72+
status: GRPC.Status.unauthenticated()
73+
}
74+
end
75+
6376
def say_hello(_req, _stream) do
6477
raise GRPC.RPCError, status: GRPC.Status.unauthenticated(), message: "Please authenticate"
6578
end
@@ -172,6 +185,32 @@ defmodule GRPC.Integration.ServerTest do
172185
end)
173186
end
174187

188+
test "return errors for handled errors" do
189+
run_server([HelloErrorServer], fn port ->
190+
{:ok, channel} = GRPC.Stub.connect("localhost:#{port}")
191+
req = Helloworld.HelloRequest.new(name: "handled error")
192+
{:error, reply} = channel |> Helloworld.Greeter.Stub.say_hello(req)
193+
194+
assert %GRPC.RPCError{
195+
status: GRPC.Status.unauthenticated(),
196+
message: "Please authenticate"
197+
} == reply
198+
end)
199+
end
200+
201+
test "return errors for handled errors with the default message of the status" do
202+
run_server([HelloErrorServer], fn port ->
203+
{:ok, channel} = GRPC.Stub.connect("localhost:#{port}")
204+
req = Helloworld.HelloRequest.new(name: "handled error without message")
205+
{:error, reply} = channel |> Helloworld.Greeter.Stub.say_hello(req)
206+
207+
assert %GRPC.RPCError{
208+
status: GRPC.Status.unauthenticated(),
209+
message: "The request does not have valid authentication credentials for the operation"
210+
} == reply
211+
end)
212+
end
213+
175214
test "returns appropriate error for stream requests" do
176215
run_server([FeatureErrorServer], fn port ->
177216
{:ok, channel} = GRPC.Stub.connect("localhost:#{port}")

0 commit comments

Comments
 (0)