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

Javascript fetch()未捕获自定义错误消息,javascript,fetch-api,catch-block,Javascript,Fetch Api,Catch Block,我有以下fetch()api,但catch块工作不正常。我收到的错误消息是: SyntaxError: Unexpected token < in JSON at position 0 undefined 以下是api: const getBtn = document.getElementById('get-btn') const postBtn = document.getElementById('post-btn') const sendHttpRequest = (method

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

SyntaxError: Unexpected token < in JSON at position 0 undefined
以下是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)

如果要捕获承诺中的错误,应该使用
.catch()
而不是
。然后()

为了查看正文是否可以解析为JSON,需要调用承诺中的
.JSON
。这将返回一个承诺,该承诺要么解析为已解析的值,要么由于主体不可解析而抛出

如果它不可解析,
。则连接到它的
s将不会运行
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
内的
抛出错误将导致承诺被拒绝,因此
getData
.catch
将看到错误。

。然后(errResData=>{
您需要
.catch(errResData=>{
如果您想捕获错误…它可能是404而不是像代码所期望的那样返回json,而是返回html吗?通常html文档中的第一个字符是
我猜
response.json()
失败了,而且你永远也不会捕获到那一个。看看你现在看到了什么,我很确定里面有一些HTML而不是JSON。@robo Robok实际的url是localhost/async/fetch/data.JSON或data.php。我在两者中都添加了一个x来创建一个404错误。我遵循你的建议,但相信你可能忽略了一个潜在的问题。什么如果我们有一个错误,但response.json()返回,则不会发生这种情况。我认为我们需要一个.then和一个.catch。你是什么意思,
但是response.json()返回
?如果根据您的问题,您希望在此处捕获的错误消息是
SyntaxError:Unexpected token<在JSON中的位置0未定义
,则添加
。catch
而不是
。则
将正确捕获不可解析的JSON。是的,这是正确的,但只是因为response.JSON()不起作用。假设返回的响应为null,将永远不会调用抛出错误,因为它位于catch而不是then
中。json
不起作用只是因为响应不可json解析。
fetch
无论如何都不能返回
null
类型的对象-它将始终是
response
类型的对象。如果要检查PARed结果不是空的,在另一个
中执行该操作。然后在调用
.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()
.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()