首页 文章

使用状态为500的fetch api读取json内容的更好方法[重复]

提问于
浏览
-2

这个问题在这里已有答案:

处理错误处理问题,我需要根据返回的状态代码捕获错误 . 另外,我需要获取响应的主体以获取特定的错误消息 . 我创建了一个粗略的脚本,如下所示:

let status = 200;
return fetch('/someurl',{ credentials: 'include' })
        .then(res => {
             if(!res.ok) {
                 status = res.status;
             }
             return res.json();
         })
        .then(json => {
            if(status < 200 || status >= 300) {
                notifyError(status, json);
            }
            treatResponse(json);
        })
        .catch(err => notifyError(err));

这段代码按照我的预期工作,但它不是我所期望的代码质量,因为我使用全局变量来通知接下来然后发生了什么......非常难看 .

我认为我的代码反映了这样一个事实,即我对fetch api和我承诺的这些承诺很新,但我并不熟悉 .

有人可以更好地吸取更多东西吗?

谢谢

2 回答

  • 0

    您可以通过使用Promise.all()将promise传递给promise数组来将其转换为此:

    return fetch('/someurl', { credentials: 'include' })
      .then(res => Promise.all([res.status, res.json()]))
      .then(([status, json]) => {
        if (status < 200 || status >= 300) {
          notifyError(status, json)
        }
    
        treatResponse(json)
      })
      .catch(err => notifyError(err))
    
  • -2

    只需抛出错误并在 catch 块上捕获该错误 -

    return fetch('/someurl',{ credentials: 'include' })
            .then(res => {
                 if(!res.ok) {
                     throw Error('something');
                 }
                 return res.json();
             })
            .then(json => {
                if(status < 200 || status >= 300) {
                    throw Error('something othere');
                }
                treatResponse(json);
            })
            .catch(err => notifyError(err));
    

    可能是这个帮助 - read

相关问题