Yuj*_*ong 5 javascript try-catch jsx reactjs
所以我对行业标准的实施感到困惑。我觉得我现在这样做的方式很奇怪
我想在出现实际错误时显示错误消息,并在服务器返回不成功状态时显示失败消息
这里的问题是,当 allocateUser() 上出现实际错误时,它会返回错误,并且这不会触发第一个函数的 catch,因此它由 else 语句处理,并在实际错误时显示失败消息。我尝试在 allocateUser() 的捕获中使用 throw new Error("error) 但同样的问题。
我的第二个问题是(200 >= status <300)除了检查状态(可以是 200、204 ...)之外,是否有更简单的方法来检查操作是否成功?
try {
let status = assignUser(user);
if (status >= 200 && status < 300) {
notify.show("message success");
} else {
notify.show("message failure");
}
} catch (e) {
notify.show("message error");
}
export async function assignUser(user) {
try {......
return resp.status;
} catch (e) {
return e;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 2
我假设 allocateUser 函数正在使用 fetch 进行 api 调用。因此,如果您不使用 then catch 方法来解析 Promise,则 allocateUser 函数必须是异步函数。
async function assignUser(user) {
try {
const jsonRes = await fetch(url);
if(!jsonRes.ok) {
notify.show("message failure");
} else {
notify.show("message success");
const result = await jsonRes.json();
return result;
}
} catch (e) {
notify.show("message error");
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,您不需要其他函数来检查状态和所有内容,您可以使用 response.ok 属性来代替检查状态代码。
希望这有帮助谢谢
| 归档时间: |
|
| 查看次数: |
1405 次 |
| 最近记录: |