封装后的 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')
      }
    }

问题:

  1. 老师,您好! 个人理解,这里如果 post 的 url 错误, 应该是会catch 异常,然后打印 “request failed”, 但是还是进入了 try 里面的 if 判断,并且打印了 “login failed”;
    尝试在 request.js 中 catch 并 throw 没有达到预期效果。

老师第九章这个code也是没有打印 ‘request failed’, 即使 url 错误。

  1. 个人理解, 前端只能传到后端 的 data.key 为 userName 和 password, 但是为什么 将 userName 改成 name,也是返回成功呢?
写回答

1回答

Dell

2021-05-04

  1. 不对,try catch 是你逻辑异常才会执行,url 并不会出这个问题

  2. 因为这是mock的接口,不是真正的接口

0
4
farmer_code
回复
Dell
明白了
2021-06-07
共4条回复

Vue3入门与项目实战 掌握完整知识体系

明星讲师DELL亲授,全方位知识点+高匹配度项目,入门到深度掌握

3382 学习 · 1454 问题

查看课程