fetch() 未捕获自定义错误消息

fetch() not catching custom error message

我有以下 fetch() api 但 catch 块无法正常工作。我收到的错误消息是:

SyntaxError: Unexpected token < in JSON at position 0 undefined

但我期待的是:

something went wrong null

这是 api:

const getBtn = document.getElementById('get-btn')
const postBtn = document.getElementById('post-btn')


const sendHttpRequest = (method, url, data) => {
    return fetch(url, {
        method: method,
        body: JSON.stringify(data),
        headers: data ? {'Content-Type': 'application/json'} : {}
    })
        .then(response => {
            console.log(response.status)
            if(response.status >= 400 || response == null){
                return response.json()
                    .then(errResData => {
                        const error = new Error('something went wrong')
                        error.data = errResData
                        throw error;
                    })
            }
            return response.json()
    })
}

const getData = () =>{
    sendHttpRequest('GET','http://localhost/async/fetch/data.jsonx')
        .then(responseData => {
            console.log(responseData)
        })
        .catch(err =>{
            console.log(err,err.data)
        })

}

const sendData = () =>{
    sendHttpRequest('POST','http://localhost/async/fetch/data.phpx',{
        email: 'someemail@gmail.com',
        password: 'compas'
    })
        .then(responseData => {
            console.log(responseData)
        })
        .catch(err => {
            console.log(err,err.data)
        })
}


getBtn.addEventListener('click',getData)
postBtn.addEventListener('click',sendData)

如果你想从 Promise 中捕获错误,你应该使用 .catch() 而不是 .then()

为了查看正文是否可解析为 JSON,您需要在 Promise 上调用 .json。这将 return 一个 Promise,要么解析为已解析的值,要么由于正文不可解析而抛出。

如果它不可解析,.then 连接到它就不会 运行;如果正文不可解析, return response.json().then 将不起作用,因此解释器永远不会到达 new Error('something went wrong')

.then(response => {
    console.log(response.status)
    if(response.status >= 400 || response == null){
        return response.json()
            .then(errResData => {
                const error = new Error('something went wrong')
                error.data = errResData
                throw error;
            })
    }
    return response.json()

应该是

.then(response => {
    console.log(response.status)
    if(response.status >= 400 || response == null){
        return response.json()
            .catch(errResData => {
                const error = new Error('something went wrong')
                error.data = errResData
                throw error;
            })
    }
    return response.json()

如果不可解析的响应将始终满足条件 response.status >= 400 || response == null

编辑代码中 .catch 中的 throw error 将导致 Promise 被拒绝,因此 getData.catch 将看到错误。