reactjstypescriptnext.jsaxios

Set type error try catch on typescript except error.message


I created a custom error message sent from the server side, of course I don't just use

error.message

to get the message. So I use

error.response.data

to get the message and get an error like the code below.

const handleLogin = async (formData: FormData) => {
  const email = formData.get("email");
  const password = formData.get("password");

  axios
    .get("http://localhost:8000/sanctum/csrf-cookie")
    .then(async () => {
      try {
        const response = await axios.post(
          "http://localhost:8000/api/login",
          {
            email,
            password,
          },
          {
            headers: {
              Accept: "application/json",
              "Content-Type": "application/json",
            },
          }
        );

        console.log(response.data);
      } catch (error: unknown) {
        console.log((error as Error).response.data); // Property 'response' does not exist on type 'Error'.
      }
    })
    .catch((error) => {
      console.log(`Error: ${error.message}`);
    });
};

please help me solve this, i really appreciate it


Solution

  • You’re encountering this issue because the default Error type in TypeScript doesn’t have a response property. When using Axios, errors are typically of the AxiosError type, which includes response.

        import axios, { AxiosError } from "axios";
    
    const handleLogin = async (formData: FormData) => {
      const email = formData.get("email");
      const password = formData.get("password");
    
      try {
        await axios.get("http://localhost:8000/sanctum/csrf-cookie");
        try {
          const response = await axios.post(
            "http://localhost:8000/api/login",
            { email, password },
            {
              headers: {
                Accept: "application/json",
                "Content-Type": "application/json",
              },
            }
          );
          console.log(response.data);
        } catch (error) {
          if (axios.isAxiosError(error)) {
            console.error(error.response?.data); // Use optional chaining to avoid undefined errors
          } else {
            console.error("An unexpected error occurred:", error);
          }
        }
      } catch (error) {
        console.error(`Error during CSRF request: ${error.message}`);
      }
    };