Skip to content

Commit b6042f1

Browse files
authored
Merge pull request #32 from julia-vscode/return-type-check
Add return type check for handlers
2 parents 0bb9f34 + be4b101 commit b6042f1

File tree

2 files changed

+41
-1
lines changed

2 files changed

+41
-1
lines changed

src/typed.jl

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ end
1818

1919
get_param_type(::NotificationType{TPARAM}) where {TPARAM} = TPARAM
2020
get_param_type(::RequestType{TPARAM,TR}) where {TPARAM,TR} = TPARAM
21+
get_return_type(::RequestType{TPARAM,TR}) where {TPARAM,TR} = TR
2122

2223
function send(x::JSONRPCEndpoint, request::RequestType{TPARAM,TR}, params::TPARAM) where {TPARAM,TR}
2324
res = send_request(x, request.method, params)
@@ -68,8 +69,12 @@ function dispatch_msg(x::JSONRPCEndpoint, dispatcher::MsgDispatcher, msg)
6869
if handler.message_type isa RequestType
6970
if res isa JSONRPCError
7071
send_error_response(x, msg, res.code, res.msg, res.data)
71-
else
72+
elseif res isa get_return_type(handler.message_type)
7273
send_success_response(x, msg, res)
74+
else
75+
error_msg = "The handler for the '$method_name' request returned a value of type $(typeof(res)), which is not a valid return type according to the request definition."
76+
send_error_response(x, msg, -32603, error_msg, nothing)
77+
error(error_msg)
7378
end
7479
end
7580
else

test/test_typed.jl

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,4 +59,39 @@
5959

6060
fetch(server_task)
6161

62+
# Now we test a faulty server
63+
64+
server_is_up = Base.Condition()
65+
66+
server_task2 = @async begin
67+
server = listen(global_socket_name)
68+
notify(server_is_up)
69+
sock = accept(server)
70+
global conn = JSONRPC.JSONRPCEndpoint(sock, sock)
71+
global msg_dispatcher = JSONRPC.MsgDispatcher()
72+
73+
msg_dispatcher[request2_type] = (conn, params)->34 # The request type requires a `String` return, so this tests whether we get an error.
74+
75+
run(conn)
76+
77+
for msg in conn
78+
@test_throws ErrorException("The handler for the 'request2' request returned a value of type $Int, which is not a valid return type according to the request definition.") JSONRPC.dispatch_msg(conn, msg_dispatcher, msg)
79+
end
80+
end
81+
82+
wait(server_is_up)
83+
84+
sock2 = connect(global_socket_name)
85+
conn2 = JSONRPCEndpoint(sock2, sock2)
86+
87+
run(conn2)
88+
89+
@test_throws JSONRPC.JSONRPCError(-32603, "The handler for the 'request2' request returned a value of type $Int, which is not a valid return type according to the request definition.", nothing) JSONRPC.send(conn2, request2_type, nothing)
90+
91+
close(conn2)
92+
close(sock2)
93+
close(conn)
94+
95+
fetch(server_task)
96+
6297
end

0 commit comments

Comments
 (0)