Back

How to filter Login error response?

  • 0
  • Web
xmaniaxz
29 Feb, 2024, 14:09

As the title says. I want to log my users in but sometimes they get an error. For instance password too short or maybe credentials dont match.

Is there a way i can catch the error type and turn that into a variable i can use.

TypeScript

  const IsLoggedIn = async () => {
    try {
      var res = await account.get();
      if (res) {
        redirectTo("./homepage");
      }
    } catch (e) {
      setLoading(false);
    }
  };

  async function handleLogin() {
    try {
      setLoading(true);
      await account.createEmailSession(email, password);
      setPassword("");
      setLoading(false);
      IsLoggedIn();
    } catch (error) {
      console.error(error);
      setLoading(false);
    }
  }

  async function handleRegister() {
    try {
      setLoading(true);
      await account.create(ID.unique(), email, password);
      setPassword("");
      setLoading(false);
      IsLoggedIn();
    } catch (error) {
      console.error(error);

      setLoading(false);
    }
  }

  const redirectTo = (path) => {
    router.replace(path);
  };

  useEffect(() => {
    IsLoggedIn();
  }, []);
TL;DR
Developers seek help in filtering login error responses. They discuss using setLoading and try-catch blocks. Utilizing 'finally' for setLoading(false) in both try and catch is recommended. Error type can be extracted using 'error as Error' and 'error.message' for displaying to users. Users wonder about handling errors like password being too short or incorrect credentials. The provided code snippets show how to handle login and registration processes, including error-catching and navigating.
Kenny
29 Feb, 2024, 14:28

A bit off of what you've asked but instead of doing setLoading(false) in both the try and catch I believe you can utilize finally and put it there.

Kenny
29 Feb, 2024, 14:29

If you want the specific error message you can do error as Error and then error.message to get the specific error message, and use that to display to the user.

xmaniaxz
29 Feb, 2024, 14:31

ill try it out.

setLoading was first so i could have a spinner.

Kenny
29 Feb, 2024, 14:32

Sure, you can do setLoading(true) outside the try catch and add a finally block to the trycatch to set loading to false.

Kenny
29 Feb, 2024, 14:33

Maybe something like

TypeScript
setLoading(true)
try {
...something
} catch (error) {
  if(error instanceof Error) {
    setError(error.message)
  }
} finally {
  setLoading(false)
}
mandolfo
29 Feb, 2024, 14:47

On AppwriteException catch (e) { }

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more