如何尝试捕获`response.text()`中的错误`Uncaught (in Promise) TypeError: Body is unusable`?

问题描述 投票:0回答:1
  1. 我尝试从服务器获取响应
     let fetchResponse;
     try {
       fetchResponse = await fetch(url, {
         method: 'POST',
         headers: {
           'Content-type': 'application/json',
           Accept: 'application/json,*/*;q=0.0',
         },
         body: JSON.stringify(codeConversionInputMsg),
       });
     } catch (error) {
       throw new FetchApiErrorWrapper(); // (dont worry, this line doesnt reach, its not the problem)
     }
    
  2. 服务器崩溃并返回
    500
  3. 我尝试拿到
    fetchResponse.text()
    看看里面有什么
  4. 但是
    fetchResponse.text()
    抛出错误
  5. 所以我想捕获
    fetchResponse.text()
  6. 中的错误
  7. 我抓不到它,它一直在扔
    Uncaught (in promise) TypeError: Body is unusable

    里面好像还有另一个承诺什么的?我怎样才能抓住它?
     } else if (fetchResponse.status >= 400 && fetchResponse.status < 600) {
           let msg
           try {
             msg = await fetchResponse.text(); // << here is the problem
           } catch (error) {
             msg = undefined; // this line is never reached
           }
    }
    
javascript error-handling promise fetch-api
1个回答
-1
投票

fetch() 函数的返回值是一个解析为 Response 对象的 Promise。 然后您将使用这个 Response 对象。请参阅示例。您都做错了,因此请使用示例进行更正。

© www.soinside.com 2019 - 2024. All rights reserved.