FlameDra
FlameDra

Reputation: 2087

How to handle Promise that returns a 404 status?

I have a method that uses node-fetch to make a POST call to update a profile object in a table via an API. If an invalid profileId is provided (status 404) the promise still resolves. What's the best way to handle it so that I can only accept status 200? The method is defined as:

async function updateUserProfileSocketId(profileId, socketId) {
    const body = { id: profileId, socketId };
    try {
        const response = await fetch(`${API_URL}/updateUserProfile`, {
            method: 'post',
            body: JSON.stringify(body),
            headers: { 'Content-Type': 'application/json' },
        });

        if (response.status !== 200) {
            throw new Error(response.status);
        }
    } catch (err) {
        console.log(`updateUserProfileSocketId Error: ${err}`);
    }
}

And the method is called in a service class like this:

onInit(socket) {
    socket.on('init', (profile) => {
        Promise.resolve(updateUserProfileSocketId(profile.id, socket.id))
            .then((response) => {
                if (response === null || response === undefined) {
                    console.log(`Unable to find profile ${profile.id}`);
                    socket.conn.close();
                } else {
                    users.push(profile.id);
                }
            })
            .catch((err) => {
                console.log(err);
            });
    });
}

This seems to work, but I'm not sure if this is the best way to handle this. Any ideas?

Upvotes: 1

Views: 2656

Answers (1)

eol
eol

Reputation: 24555

If the response status is not 200, you throw an exception that will immediately be caught again. This is probably not what you want. You can leave the catch block for logging purposes, but you should rethrow the exception:

async function updateUserProfileSocketId(profileId, socketId) {
    const body = { id: profileId, socketId };
    try {
        const response = await fetch(...);

        if (response.status !== 200) {
            throw new Error(response.status);
        }
    } catch (err) {
        console.log(`updateUserProfileSocketId Error: ${err}`);
        throw err;
    }
}

The same thing applies to the catch-handler inside the socket-callback. However, removing the try/catch/log/rethrow logic and handling the exception centrally would be cleaner.

Upvotes: 1

Related Questions