From b7ed528ab025d3bd06349a9aa67d26581d096922 Mon Sep 17 00:00:00 2001 From: Shohei Maeda <11495867+smaeda-ks@users.noreply.github.com> Date: Mon, 23 Jan 2023 03:29:28 +0900 Subject: [PATCH] handle errors --- pages/api/generate.ts | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/pages/api/generate.ts b/pages/api/generate.ts index 90312ee3..e6ece065 100644 --- a/pages/api/generate.ts +++ b/pages/api/generate.ts @@ -58,15 +58,20 @@ const handler = async (req: NextRequest): Promise => { controller.close(); return; } - const json = JSON.parse(data); - const text = json.choices[0].text; - if (counter < 2 && (text.match(/\n/) || []).length) { - // this is a prefix character (i.e., "\n\n"), do nothing - return; + try { + const json = JSON.parse(data); + const text = json.choices[0].text; + if (counter < 2 && (text.match(/\n/) || []).length) { + // this is a prefix character (i.e., "\n\n"), do nothing + return; + } + const queue = encoder.encode(text); + controller.enqueue(queue); + counter++; + } catch (e) { + // maybe parse error + controller.error(e); } - const queue = encoder.encode(text); - controller.enqueue(queue); - counter++; } }