繁体   English   中英

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)

为了查看主体是否可解析为 JSON,您需要在.json上调用 .json。 这将返回一个 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 response.status >= 400 || response == null

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM