diff --git a/src/LanguageServer.php b/src/LanguageServer.php index a58ada9..ae4b1b9 100644 --- a/src/LanguageServer.php +++ b/src/LanguageServer.php @@ -49,21 +49,26 @@ class LanguageServer extends AdvancedJsonRpc\Dispatcher parent::__construct($this, '/'); $this->protocolReader = $reader; $this->protocolReader->onMessage(function (Message $msg) { + $result = null; + $error = null; try { // Invoke the method handler to get a result $result = $this->dispatch($msg->body); - $responseBody = new AdvancedJsonRpc\SuccessResponse($msg->body->id, $result); - } catch (AdvancedJsonRpc\Error $error) { - // If a ResponseError is thrown, send it back in the Response (result will be null) - $responseBody = new AdvancedJsonRpc\ErrorResponse($msg->body->id, $error); + } catch (AdvancedJsonRpc\Error $e) { + // If a ResponseError is thrown, send it back in the Response + $error = $e; } catch (Throwable $e) { // If an unexpected error occured, send back an INTERNAL_ERROR error response $error = new AdvancedJsonRpc\Error($e->getMessage(), AdvancedJsonRpc\ErrorCode::INTERNAL_ERROR, null, $e); - $responseBody = new AdvancedJsonRpc\ErrorResponse($msg->body->id, $error); } // Only send a Response for a Request // Notifications do not send Responses if (AdvancedJsonRpc\Request::isRequest($msg->body)) { + if ($error !== null) { + $responseBody = new AdvancedJsonRpc\ErrorResponse($msg->body->id, $error); + } else { + $responseBody = new AdvancedJsonRpc\SuccessResponse($msg->body->id, $result); + } $this->protocolWriter->write(new Message($responseBody)); } });