[英]How to handle Promise that returns a 404 status?
我有一种方法,它使用 node-fetch 进行 POST 调用,以通过 API 更新表中的配置文件 object。 如果提供了无效的 profileId(状态 404),promise 仍然可以解决。 处理它的最佳方法是什么,以便我只能接受状态 200? 该方法定义为:
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}`);
}
}
该方法在服务 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);
});
});
}
这似乎可行,但我不确定这是否是处理此问题的最佳方法。 有任何想法吗?
如果响应状态不是 200,则抛出异常,该异常将立即再次被捕获。 这可能不是你想要的。 您可以将 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;
}
}
同样的事情也适用于 socket-callback 中的 catch-handler。 但是,删除 try/catch/log/rethrow 逻辑并集中处理异常会更干净。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.