Skip to content

Commit 7d2e993

Browse files
adi-kmte5l
andauthored
Remove the double bang operator and replace it with a null check instead. (#49)
2. add try catch in the block for transport send in acatch block Co-authored-by: Leonid Stashevsky <e5l@users.noreply.github.com>
1 parent 0a6490c commit 7d2e993

File tree

1 file changed

+19
-13
lines changed
  • src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/shared

1 file changed

+19
-13
lines changed

src/commonMain/kotlin/io/modelcontextprotocol/kotlin/sdk/shared/Protocol.kt

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ public abstract class Protocol(
209209
if (handler === null) {
210210
LOGGER.trace { "No handler found for request: ${request.method}" }
211211
try {
212-
transport!!.send(
212+
transport?.send(
213213
JSONRPCResponse(
214214
id = request.id,
215215
error = JSONRPCError(
@@ -229,24 +229,30 @@ public abstract class Protocol(
229229
val result = handler(request, RequestHandlerExtra())
230230
LOGGER.trace { "Request handled successfully: ${request.method} (id: ${request.id})" }
231231

232-
val response = JSONRPCResponse(
233-
id = request.id,
234-
result = result
232+
transport?.send(
233+
JSONRPCResponse(
234+
id = request.id,
235+
result = result
236+
)
235237
)
236-
transport!!.send(response)
237238

238239
} catch (cause: Throwable) {
239240
LOGGER.error(cause) { "Error handling request: ${request.method} (id: ${request.id})" }
240241

241-
transport!!.send(
242-
JSONRPCResponse(
243-
id = request.id,
244-
error = JSONRPCError(
245-
ErrorCode.Defined.InternalError,
246-
message = cause.message ?: "Internal error",
242+
try {
243+
transport?.send(
244+
JSONRPCResponse(
245+
id = request.id,
246+
error = JSONRPCError(
247+
code = ErrorCode.Defined.InternalError,
248+
message = cause.message ?: "Internal error"
249+
)
247250
)
248251
)
249-
)
252+
} catch (sendError: Throwable) {
253+
LOGGER.error(sendError) { "Failed to send error response for request: ${request.method} (id: ${request.id})" }
254+
// Optionally implement fallback behavior here
255+
}
250256
}
251257
}
252258

@@ -385,7 +391,7 @@ public abstract class Protocol(
385391
try {
386392
withTimeout(timeout) {
387393
LOGGER.trace { "Sending request message with id: $messageId" }
388-
this@Protocol.transport!!.send(message)
394+
this@Protocol.transport?.send(message)
389395
}
390396
return result.await()
391397
} catch (cause: TimeoutCancellationException) {

0 commit comments

Comments
 (0)