简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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