简体   繁体   English

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

[英]fetch() not catching custom error message

I have the following fetch() api but the catch blocks aren't working correctly.我有以下 fetch() api 但 catch 块无法正常工作。 The error message I get is:我得到的错误信息是:

SyntaxError: Unexpected token < in JSON at position 0 undefined

but what I'm expecting is:但我期待的是:

something went wrong null

here's the api:这是 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)

In order to see if a body is parseable as JSON, you need to call .json on the Promise.为了查看主体是否可解析为 JSON,您需要在.json上调用 .json。 That will return a Promise that either resolves to the parsed value, or will throw due to the body not being parseable.这将返回一个 Promise ,它要么解析为解析值,要么由于正文不可解析而抛出。

If it isn't parseable, .then s connected to it won't run;如果它不可解析,连接到它的.then将不会运行; return response.json().then will not work if the body isn't parseable, so the interpreter never gets to new Error('something went wrong') .如果正文不可解析, 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()

should be应该

.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()

if the non-parseable response will always fulfill the condition response.status >= 400 || response == null如果不可解析的响应将始终满足条件response.status >= 400 || response == null response.status >= 400 || response == null . response.status >= 400 || response == null

The throw error inside the .catch in the edited code will result in the Promise rejecting, so getData 's .catch will see the error.编辑代码中.catch内的throw error将导致 Promise 拒绝,因此getData.catch会看到错误。

If you want to catch an error from a Promise, you should use .catch() instead of .then()如果你想从 Promise 捕获错误,你应该使用.catch()而不是 .then( .then()

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

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