Skip to content

Commit b0331b7

Browse files
authored
Allow method handlers to return json rpc errors (#20)
1 parent c73fbdb commit b0331b7

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

pylsp_jsonrpc/endpoint.py

+22-6
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import logging
55
import uuid
66
import sys
7+
from typing import Any, Dict, Mapping
78

89
from concurrent import futures
910
from .exceptions import (JsonRpcException, JsonRpcRequestCancelled,
@@ -175,6 +176,17 @@ def _handle_cancel_notification(self, msg_id):
175176
if request_future.cancel():
176177
log.debug("Cancelled request with id %s", msg_id)
177178

179+
@staticmethod
180+
def _make_response_payload(header: Dict[str, Any], result: Any) -> Mapping[str, Any]:
181+
# return type of 'Mapping' because it should not be mutated
182+
# further from here
183+
response = dict(header)
184+
if isinstance(result, dict) and ('result' in result or 'error' in result):
185+
response.update(result)
186+
else:
187+
response['result'] = result
188+
return response
189+
178190
def _handle_request(self, msg_id, method, params):
179191
"""Handle a request from the client."""
180192
try:
@@ -195,11 +207,14 @@ def _handle_request(self, msg_id, method, params):
195207
handler_result.add_done_callback(self._request_callback(msg_id))
196208
else:
197209
log.debug("Got result from synchronous request handler: %s", handler_result)
198-
self._consumer({
199-
'jsonrpc': JSONRPC_VERSION,
200-
'id': msg_id,
201-
'result': handler_result
202-
})
210+
response = self._make_response_payload(
211+
{
212+
'jsonrpc': JSONRPC_VERSION,
213+
'id': msg_id,
214+
},
215+
handler_result,
216+
)
217+
self._consumer(response)
203218

204219
def _request_callback(self, request_id):
205220
"""Construct a request callback for the given request ID."""
@@ -216,7 +231,8 @@ def callback(future):
216231
}
217232

218233
try:
219-
message['result'] = future.result()
234+
result = future.result()
235+
message = self._make_response_payload(message, result)
220236
except JsonRpcException as e:
221237
log.exception("Failed to handle request %s", request_id)
222238
message['error'] = e.to_dict()

0 commit comments

Comments
 (0)