Skip to content

fetch错误解析 #3

@AlvinYuXT

Description

@AlvinYuXT

fetch什么时候进入reject状态

根据MDN的定义,fetch只有在遇到网络出错的情况(断网、DNS解析错误等)会reject掉,也就是说下面这种情况会打印出ok

fetch('http://httpstat.us/500')
  .then(res => { console.log('ok') })
  .catch(err => { console.log('err') })

要想正确的打印出err,只需要判断一下res.ok就可以知道网络请求是否成功,res.ok就是this.ok = this.status >= 200 && this.status < 300

因此我们只要这么写就行了

fetch('http://httpstat.us/500')
  .then(res => {
    if (res.ok) {
      return res.json()
    } else {
	  throw new Error('network err')          
    }
  })
  .catch(err => { console.log(err) })

json方法

都知道json方法就是对res.text()的结果进行JSON.parse操作,那么如果是执行res.json()出错了的话,应该怎么捕获这个错误呢?首先try/catch写法是肯定不行的,因为try/catch是无法捕获异步的异常的,而json方法返回的是个Promise

    this.json = function() {
      return this.text().then(JSON.parse)
    }

所以我想到的方法就是

let parseJSON = (response) => {
    return response.json()
        .catch(err => {
            throw new Error("JSON Parse Error")
        })
}

fetch(url).then(parseJSON).catch(err=>{console.log(err)})

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions