封装后的 catch 没有效果
来源:9-5 请求函数的封装

All_Good
2021-05-04
老师的code:
const handleLogin = async () => {
try {
const result = await post("/api/usefffr/login", {
username: data.username,
password: data.password
});
if (result?.errno === 0) {
localStorage.isLogin = true;
router.push({ name: "Home" });
} else {
showToast("登陆失败");
}
} catch (e) {
showToast(e + "请求失败");
}
};
学生的code:
// check user information after login button was clicked
const handleLogin = async () => {
try {
// resData: result.data
const resData = await post('/api/uffser/login', {
userName: data.userName,
password: data.password
})
// if throw an exception, the below code won't be executed
if (resData?.errno === 0) {
// once login successfullt, isLogin is true
localStorage.isLogin = true
// navigate to the Home page
router.push({ name: 'Home' })
} else {
showToast('login failed')
}
} catch (err) {
showToast('request failed')
}
}
问题:
- 老师,您好! 个人理解,这里如果 post 的 url 错误, 应该是会catch 异常,然后打印 “request failed”, 但是还是进入了 try 里面的 if 判断,并且打印了 “login failed”;
尝试在 request.js 中 catch 并 throw 没有达到预期效果。
老师第九章这个code也是没有打印 ‘request failed’, 即使 url 错误。
- 个人理解, 前端只能传到后端 的 data.key 为 userName 和 password, 但是为什么 将 userName 改成 name,也是返回成功呢?
写回答
1回答
-
Dell
2021-05-04
不对,try catch 是你逻辑异常才会执行,url 并不会出这个问题
因为这是mock的接口,不是真正的接口
042021-06-07
相似问题
老师删除元素时剩下的元素没有过渡效果呢
回答 2
result请求返回条件和封装的请求
回答 1
关于axios封装
回答 1
删除时,v-move 过渡效果没有生效
回答 3
关于这种封装方式的疑惑
回答 3