JavaScript:无法捕获异步函数中的错误

smtd7mpg  于 2023-01-16  发布在  Java
关注(0)|答案(2)|浏览(126)

handleEmailSubmit函数不捕捉任何错误,即使loginWithEmail函数抛出一个错误。可能是我缺乏异步函数的理解。我需要你的帮助。谢谢。
Login.tsx

const Login: React.FC = () => {
  const [errorMsg, setErrorMsg] = useState<string>('');
  const history = useHistory();

  const handleEmailSubmit = useCallback(async (e) => {
    e.preventDefault();
    const { email, password } = e.target.elements;
    loginWithEmail(email.value, password.value)
      .then(() => {
        history.push('/');
      })
      .catch((error) => {
        // this block isn't called!
        setErrorMsg(error.message);
      });
  }, []);

  return (
    <>
      <h2>Login</h2>
      <form onSubmit={handleEmailSubmit}>
        <InputGroup>
          <label htmlFor="email">Email</label>
          <TextField
            id="email"
            name="email"
            type="email"
          />
        </InputGroup>
        <InputGroup>
          <label htmlFor="password">Password</label>
          <TextField
            id="password"
            name="password"
            type="password"
          />
        </InputGroup>
        <Button type="submit">
          送信する
        </Button>
      </form>
    </>
  );
}

loginWithEmail定义

import axios from 'axios';

// firebase
import 'firebase/auth';
import firebase from 'firebase/app';

export const loginWithEmail = async (
  email: string,
  password: string
): Promise<void> => {
  app
    .auth()
    .signInWithEmailAndPassword(email, password)
    .then((userCredential) => {
      userCredential.user?.getIdToken(true).then((token: string) => {
        axios
          .get('https://dev.myserver.com/api/v1/users/auth', {
            headers: { Authorization: `Bearer ${token}` },
          })
          .catch((error) => {
            app.auth().signOut();
            throw error;
          });
      });
    })
    .catch((error) => {
      console.log(error);
    });
};
bqujaahr

bqujaahr1#

要从异步函数中捕获错误,可以使用try/catch并等待错误:

const handleEmailSubmit = useCallback(async (e) => {
  e.preventDefault();
  const { email, password } = e.target.elements;
  try {
    await loginWithEmail(email.value, password.value);
    history.push('/');
  } catch(error) {
    const message = await error.message;
    setErrorMsg(message);
  }
}, []);
qxsslcnc

qxsslcnc2#

您需要在catch语句中抛出错误。

app
    .auth()
    .signInWithEmailAndPassword(email, password)
    .then((userCredential) => {
      userCredential.user?.getIdToken(true).then((token: string) => {
        axios
          .get('https://dev.myserver.com/api/v1/users/auth', {
            headers: { Authorization: `Bearer ${token}` },
          })
          .catch((error) => {
            app.auth().signOut();
            throw error;
          });
      });
    })
    .catch((error) => {
      console.log(error);
      throw error; // there could be something wrong here
      
    });

相关问题