Tips for detecting and handling uncaught TypeErrors in a GPT chatbot live stream by utilizing fetch and getReader functions within a Vue3

I am currently working on a chatbot client using the Vue3 composition api. My backend is built on fastapi and has a post endpoint that returns a StreamingResponse. To handle this on the UI, I have implemented a fetch request that utilizes the getReader method: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream/getReader

try {
  fetch('api...', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: jsonPrompt
  })
  .then(response => {
    if (!response.ok || !response.body) {
      return;
    }
  
    const reader = response.body.getReader();
  
    reader.read().then(function processText({ done, value }) {
      if (done) {
        console.log('Stream done');
        return;
      }
    
      const decodedData = new TextDecoder('utf-8').decode(value);
      console.log('decodedData:', decodedData);
      //processStream(decodedData);
    
      return reader.read().then(processText);
    })
  })
  .catch(error => {
    console.error('Error in promise:', error);
  });
}
catch (error) {
  console.error('Error:', error);
}

Sometimes, I encounter a TypeError: network error during the processing of chunks from getReader, even though the stream has started, and before the done flag returns true, with the response status code being 200!?

net::ERR_HTTP2_PROTOCOL_ERROR 200 (OK)
Furthermore, the try catch block surrounding the fetch operation does not capture this specific error:

https://i.sstatic.net/82lbrNET.png

Any suggestions on how to handle and catch this particular error while processing chunks from getReader?

Answer №1

In the event that the network connection drops while data is being transmitted, such as after headers have already been sent (resulting in fetch returning a fulfilled promise), it is possible for issues to arise. If you do not utilize await with reader.read(), a rejected promise may be returned instead of an error being thrown. Additional information can be found in the topic of Asynchronous Programming.

Considering this situation, I would recommend using fetch-event-stream instead, or at least examining its implementation for guidance.

Answer №2

The resolution came quite easily: I opted for async await over using a promise then().catch() method, as demonstrated in the Streams API, allowing me to successfully handle the Network error.

This is the straightforward adjustment to the code structure:

const fetchData = async () => {
  try {
    const result = await fetch('url', {});
    for await (const chunk of result.body) {
      console.log('Processing next chunk:', chunk);
    }
  } catch (error) {
    console.log('Encountered Error:', error);
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to add JavaScript files while conducting React component testing?

Currently, I am in the process of writing a test for a React component that is using the selectpicker JavaScript library. Below is the Mount method implementation: componentDidMount() { const selectControl = $(this.refs.selectName); selectControl.select ...

What is the most effective method for retrieving a key and value from an Axios response object?

I currently have a Mongoose schema set up to store key:value pairs in a mixed type array, represented like this: Mongoose const budgetSchema = new Schema({ earnings: Number, expenses: [mongoose.Schema.Types.Mixed] }); budget:{ earning:1000, exp ...

Error: The function getWidget is not defined

I'm encountering an issue while attempting to execute a function in index.php. The error message Uncaught ReferenceError: getWidget is not defined pops up when I try to call the function from widget.php, where it functions correctly. How can I make su ...

Explore the intricacies of complex hierarchies

<table id="financial101_tab1" class="dxrpControl_Moderno dxrpWithoutHeader_Moderno"> <tbody> <tr> <td id="financial101_tab1_RPC" class="dxrp dxrpcontent"> <input id="BlockControlfinancial101_tab1ATI" type= ...

Using Firebase Realtime Database, this React dropdown menu is populated with options in real-time. Combining the features

I'm currently facing an issue with a dropdown that is supposed to loop through data fetched from the Firebase realtime database. The goal is to assign a selected value to a Formik form for saving it to another object in the database. In my database, ...

Unlocking the Potential of Checkbox Values in AngularJS

I am attempting to extract data from a $rootScope object that has been linked to the checkboxes. HTML: <tr ng-repeat="system_history in SystemHistoryResponse.system_history"> <td><input type="checkbox" ng-model="versionValues[system_histor ...

Testing the jQuery UI datepicker with QUnit: A Step-by-Step Guide

As a newcomer to Qunit, I have a query that I'd like to address. I've developed a JavaScript file to incorporate a datepicker and have created a test script using Qunit. My objective is to display the calendar, choose a date, and confirm that th ...

Enhancing a Dropdown List with Jquery Using JSON Data

I am trying to populate a list using a JSON collection of objects. Here is the method that my action is returning: public ActionResult GetProductCategories() { var categories = _entities.ProductCategories.ToList(); var res ...

Having issues with AJAX and button submit while trying to upload a file using Flask

I've been attempting to incorporate a file upload feature (specifically a .csv file) using bootstrap, and then submit it by clicking on a button. I've experimented with various methods to implement the file upload functionality, but haven't ...

Struggling to retrieve data from a MongoDB database in JSON format via an API call? If you're working with JavaScript, Node.js, Express, and MongoDB, we can help you

Below is how I establish the connection to the database: > // Connecting MongoDB using MongoClient > > const MongoClient = require('mongodb').MongoClient > > const url = 'url is used' > > const dbName = 'vir ...

Deciphering the transpiled code and tracing it back to its original markup script

Is there an easy solution to convert custom markup into different formats, even with nested markings? Examples include... for \k[hello], the output is <b>hello</b> for \i[world], the output is <em>world</em> for hello &b ...

What is the purpose of calling the alert function prior to executing my

Check out my code snippet here: FIDDLE function updateHtml() { $('#n1').html('hello'); $('#n2').html('hello'); $('#n3').html('hello'); $('#n4').html('hello&apo ...

Issue with repeatedly pressing the button

Hi there! I've noticed a strange behavior in my app. The Spider-Man button works perfectly and navigates to the next screen with just one tap. However, when I try to use the Black Panther and Hulk buttons, I have to tap them multiple times before they ...

Steps for eliminating duplicates and increasing values in a Google spreadsheet chart

I am looking to populate a Google-chart table by looping through a list of objects. However, before drawing the table, I need to check for duplicates within the list. If any duplicates are found, I want to remove them and increment the count for the unique ...

Identifying when ngModel is dirty

In my application, the input fields are populated dynamically based on the API response. Each field has a corresponding set of buttons associated with it, which I only want to show when the field is edited. Here is an image of the form: https://i.sstatic ...

Is it necessary to reattach the canvas context following the utilization of transferControlToOffscreen?

Currently, I am experimenting with a project that involves running multiple simulations in different web workers. Whenever I want to check the current status of a simulation, I employ transferControlToOffscreen on a canvas element within the main thread a ...

Update the image source every 1 second with Jquery and Javascript

I've been experimenting with creating a script that dynamically changes the source of an image every two seconds based on a list. Essentially, my current approach involves using a for loop to iterate over the provided list: $(document).ready(functio ...

How can we extract word array in Python that works like CryptoJS.enc.Hex.parse(hash)?

Is there a method in Python to convert a hash into a word array similar to how it's done in JavaScript? In JavaScript using CryptoJS, you can achieve this by using: CryptoJS.enc.Hex.parse(hash), which will provide the word array. I've searched ...

Chrome Web Store issues an overly stringent warning for accessing a public API

A new Chrome Extension called FrontPage was recently created, utilizing the New York Times API. The extension sends an AJAX request to the API and receives a JSON response. However, to make this possible, specific permissions need to be set in the manifes ...

What is the most efficient method to retrieve typed characters following a '#' in a textarea using JS/jQuery?

I am currently developing an intelligent textarea that can recognize terms typed after the '#' symbol. It should be able to work in real-time for the term being typed and handle multiple instances of the '#' symbol within the same texta ...