猿问

fetch 和 async/await 没有 try/catch

我正在尝试让异步等待在没有 try/catch 的情况下工作


  return await fetch(url, options)

    .then(res => res.json())

    .catch(err => {

      throw new Error(err)

    })

这是我拨打电话的方式:


    const response = await makeApiRequest('/reset', {

        password: password1,

        code

    }, {

        noauth: true

    }).catch(err => {

        debugger;

        msg = err.message;

    });


    if (response) {

        navigateTo('/');

    }

问题是没有一个 catch 块在工作。该代码已过期并提供 401。


守着一只汪
浏览 408回答 2
2回答

绝地无双

仅当无法发出请求时,Fetch API 才会失败。如果可以,即使状态不好,fetch 也会成功执行。因为throw new Error(err)从未被调用过,所以当您尝试将 a 解析invalid string content为 json 对象 ( res.json())时,它只会被调用。我来宾,在 401 情况下,您的服务器返回一个有效的 json 字符串,例如{message: "Unauthorized"},然后res.json()工作正常,并且没有抛出任何错误。如果你想捕捉 http 错误,那么http status codeof resobject 是一个正确的方法:  return await fetch(url, options)    .then(res => {      if (res.status >= 300) { // error http status code range        throw new Error(res.status) // throw a error to the catch block      }      return res.json();    })    .catch(err => {      throw new Error(err) // catch and throw to the error of previous `.then` block    })然后再试一次。

收到一只叮咚

这就是我的工作:  return fetch(url, options)    .then(async res => {      if (!res.ok) {        const err = await res.json()        throw err.message || res.statusText      }      return res.json()    })    .catch(err => {      throw new Error(err)    })你可以这样称呼它:        const response = await myFetch('/forgot', {            email        }, {            headers: {                'x-contact': 'hello@puump.com'            }        }).catch(err => {            msg = err.message;            return;        });        if (response) {            push('/');        }
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答