Handling Errors in Streaming Responses

When consuming server-sent streams (e.g., Axios with responseType ‘stream’), parse error payloads via stream events and throw structured errors.

Jul 14, 2024 · 1 min read · 148 Words · -Views -Comments · Digital Life
JavaScript Axios 🇨🇳 阅读中文版
Read with AI

Choose an AI assistant

ChatGPT Open in a new tab with the article link and prompt
Claude Copy the prompt, then open Claude

Open Claude
Trouble reading the article?

If the prompt is missing, copy the full prompt below into your AI assistant. If the AI cannot read the article, paste the visible passage you want to discuss and add your question.

AI APIs often return server-sent streams. When the server reports an error, the payload still arrives as a stream, so error handling differs from typical JSON responses.

Example

Using Axios as an example:

axios.post('http://api.com/v1/chat/completions', data, {
  headers: {
    Authorization: `Bearer xxxx`,
    'Content-Type': 'application/json',
  },
  responseType: 'stream',
})
  .then(res => res.data)
  .catch(async (e) => {
    let error;
    if (e.isAxiosError) {
      let streamString = '';
      await new Promise(resolve => {
        e.response.data
          .on('data', (utf8Chunk) => {
            streamString += utf8Chunk;
          })
          .on('end', () => {
            error = JSON.parse(streamString);
            resolve();
          });
      });
    } else {
      error = e;
    }
    throw error;
  });

In streaming mode you must consume the error payload through the same evented interface as normal data. Wrapping the listener with a Promise ensures you capture the full string before parsing and rethrowing.

Final Thoughts

When dealing with streaming APIs, remember that error paths are still streams—structure your error handling accordingly.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover