1
votes

I have the following fetch() api but the catch blocks aren't working correctly. 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:

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: '[email protected]',
        password: 'compas'
    })
        .then(responseData => {
            console.log(responseData)
        })
        .catch(err => {
            console.log(err,err.data)
        })
}


getBtn.addEventListener('click',getData)
postBtn.addEventListener('click',sendData)
2
.then(errResData => { you need .catch(errResData => { if you want to capture errors... - CertainPerformance
could it be a 404 and instead of it returning json like the code is expecting, its returning html? normally the first char in a html document is <, hence the error. (though looking at data.phpx, it could be <?php) - Lawrence Cherone
I would guess that response.json() fails and you never catch that one - Dominik
See what you have at localhost/async/fetch/data.jsonx, I'm pretty sure there's some HTML in there instead of JSON. - Robo Robok
@robo Robok the actual url is localhost/async/fetch/data.json or data.php. I added an x to both to create a 404 error - DCR

2 Answers

1
votes

In order to see if a body is parseable as JSON, you need to call .json on the Promise. That will return a Promise that either resolves to the parsed value, or will throw due to the body not being parseable.

If it isn't parseable, .thens connected to it won't run; return response.json().then will not work if the body isn't parseable, so the interpreter never gets to 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.

The throw error inside the .catch in the edited code will result in the Promise rejecting, so getData's .catch will see the error.

0
votes

If you want to catch an error from a Promise, you should use .catch() instead of .then()