欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

fetch异常状态处理

程序员文章站 2022-04-25 19:30:34
...
function CheckRequest(response) {
    if (!response.ok) {
        var error = new Error(response.statusText)
        error.response = response
        throw error
    } else {
        return response.json()
    }
}

fetch(URL, {method: 'POST', body: MyData, credentials: 'include'})
    .then(CheckRequest)
    .then(function(ResData) {
        console.log('request succeeded with JSON response', ResData)
    }
    .catch(function(error) {
        console.log('request failed', error)
    })