From 79e6b13295faed382497c5cf5f943cbe505a4932 Mon Sep 17 00:00:00 2001 From: Tiscs Date: Tue, 9 Jan 2024 00:40:58 +0800 Subject: [PATCH] Handler AbortError when reading stream using Fetch API --- app/clients/grpc.client.ts | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/app/clients/grpc.client.ts b/app/clients/grpc.client.ts index 2f4184f..a764f7e 100644 --- a/app/clients/grpc.client.ts +++ b/app/clients/grpc.client.ts @@ -35,17 +35,17 @@ export async function* fetchStream, O extends Message>( mn: string, rs: AbortSignal | null = null, ): AsyncGenerator { - const resp = await fetch(`${window.env.GOMMERCE_GRPC_ENDPOINT}/${sn}/${mn}`, { - method: "POST", - body: req.toJsonString(), - headers: { "Content-Type": "application/json" }, - signal: rs, - }); - const decoder = new TextDecoder("utf-8"); - const reader = resp.body?.getReader(); - let buffer = ""; - while (reader) { - try { + try { + const resp = await fetch(`${window.env.GOMMERCE_GRPC_ENDPOINT}/${sn}/${mn}`, { + method: "POST", + body: req.toJsonString(), + headers: { "Content-Type": "application/json" }, + signal: rs, + }); + const decoder = new TextDecoder("utf-8"); + const reader = resp.body?.getReader(); + let buffer = ""; + while (reader) { const { done, value } = await reader.read(); if (value && value.length > 0) { buffer += decoder.decode(value); @@ -54,17 +54,17 @@ export async function* fetchStream, O extends Message>( const chunks = buffer.split(/\r?\n/); buffer = chunks.pop() || ""; for (const chunk of chunks) { - yield mt.fromJsonString(chunk); + yield mt.fromJson(JSON.parse(chunk).result); } } if (done) { break; } - } catch (err) { - if (err instanceof DOMException && err.name === "AbortError") { - break; - } - throw err; } + } catch (err) { + if (err instanceof DOMException && err.name === "AbortError") { + return; + } + throw err; } }