user1283776
user1283776

Reputation: 21764

Throw an error to a catch handler and ignore then functions?

I have a helper function:

function httpRequestHelper(body) {
    return fetch(`${host}:${port}`, {
        method: 'post',
        body: JSON.stringify(body)
    })
    .then(function (response) {
        if (!response.ok) {
            throw Error(response.statusText);
        }
        return response.json();
    })
    .then(function(response) {
        if (response.type === 'error') {
            throw Error(response);
        }
        return response;
    })
    .catch(function(error) {
        return error;
    });    
}

that I wrote to keep functions for various commands short. These functions just specify the body to be sent and what part of the response is relevant to the consumer:

function hasActiveProject() {
    return httpRequestHelper({ type: 'request', cmd: 'has_active_project' })
    .then(function (response) {
        return response.payload.value;
    })
}

I execute the various commands like this:

try {
    let hasActiveProjectResponse = await otii.hasActiveProject()
    console.log(hasActiveProjectResponse);    
} catch (error) {
    console.log(error);
}

Now the problem is that in the catch function I would expect to get the error message thrown, but instead I get error messages like:

TypeError: Cannot read property 'value' of undefined

This is because hasActiveProject() tries to extract the relevant response even when there was an error and that causes a different error that is returned to my catch (error) handler.

How can I rewrite this so that

Upvotes: 0

Views: 37

Answers (1)

Art3mix
Art3mix

Reputation: 1307

Are you sure you have an error? and response.payload is not undefined? because in this test fiddle you can see that its working as you want it to, the try catches the errors thrown inside the .then function, and doesn't continue.

https://jsfiddle.net/8qe1sxg4/6/

It looks like response.type is valid, so you don't have any errors thrown, can you confirm the results you get?

UPDATE

After some more researching, the catch function doesn't bubble to the next catch, it considered as if you already handled the error and continue as usual (with the resolved value from the catch). But you can simply reject again inside the .catch(), so this way your error will bubble to the try/catch:

in httpRequestHelper():

.catch(function(error) {
    return Promise.reject(error)
    //return error;
});

This will send your error to the next catch, see fiddle for example: https://jsfiddle.net/dcuo46qk/3/

Upvotes: 1

Related Questions