代码之家  ›  专栏  ›  技术社区  ›  Evanss

返回新错误出现在then not catch函数中?

  •  0
  • Evanss  · 技术社区  · 6 年前

    我有一个登录函数,当登录尝试失败时返回一个错误:

    export const login = async () => {
      try {
        // Code to get res
    
        if (res.status === 200) {
          document.cookie = `userToken=${data.token}`;
        } else if (res.status === 400) {
          return new Error("Oh noo!!!");
        }
      } catch (err) {
        alert('err!! ', err);
      }
    };
    

    登录表单使用以下命令调用它:

    submit = async event => {
        login()
          .then(res => {
            console.log('res ', res);
          })
          .catch(err => {
            console.log('err ', err);
          });
      };
    

    当res.status为400并且返回错误时,它将出现在 then 功能不是 catch 功能。我怎样才能让它出现在 抓住 功能?我认为这是最佳实践,因为登录尝试失败。

    2 回复  |  直到 6 年前
        1
  •  0
  •   CertainPerformance    6 年前

    return catch

    } else if (res.status === 400) {
      throw new Error("Oh noo!!!");
    }
    

    submit try login

    export const login = async () => {
      if (res.status === 200) {
        document.cookie = `userToken=${data.token}`;
      } else if (res.status === 400) {
        throw new Error("Oh noo!!!");
      }
    };
    
        2
  •  0
  •   Luca Kiebel    6 年前

    throw throw ... catch try

    export const login = async () => {
      try {
        // Code to get res
    
        if (res.status === 200) {
          document.cookie = `userToken=${data.token}`;
        } else if (res.status === 400) {
          throw Error("Oh noo!!!");
        }
      } catch (err) {
        alert('err!! ', err);
      }
    };