简体   繁体   English

如何处理返回 404 状态的 Promise?

[英]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.我有一种方法,它使用 node-fetch 进行 POST 调用,以通过 API 更新表中的配置文件 object。 If an invalid profileId is provided (status 404) the promise still resolves.如果提供了无效的 profileId(状态 404),promise 仍然可以解决。 What's the best way to handle it so that I can only accept status 200?处理它的最佳方法是什么,以便我只能接受状态 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:该方法在服务 class 中调用,如下所示:

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.如果响应状态不是 200,则抛出异常,该异常将立即再次被捕获。 This is probably not what you want.这可能不是你想要的。 You can leave the catch block for logging purposes, but you should rethrow the exception:您可以将 catch 块保留为记录目的,但您应该重新抛出异常:

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.同样的事情也适用于 socket-callback 中的 catch-handler。 However, removing the try/catch/log/rethrow logic and handling the exception centrally would be cleaner.但是,删除 try/catch/log/rethrow 逻辑并集中处理异常会更干净。

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

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