Search code examples
javascripttypescriptnext.jsaxiosfastapi

How to display error body on front end using axios


My fast api end point is here:

@app.post("/api/signup", status_code=status.HTTP_200_OK)
async def signup( credentials : signupcred ):
  try: 
   print(credentials.email,  credentials.password1, credentials.name )
   response = account.create(email= credentials.email, password= credentials.password1, name = credentials.name , user_id= ID.unique() )

   return {response}

  except Exception as e: 
         raise HTTPException(status_code= status.HTTP_403_FORBIDDEN)  # Return an appropriate error status code

on the front end, i want to print the response after an exception has been raised because the response explains the error well. I don't want to send a http error code to the user.

my front end is :

const handlesignup = async (e: any) => {
  e.preventDefault();
  setLoading((loading) => !loading);
  try {
    const signupresponse = await axios.post("/api/signup", {
      email: signupemail,
      password1: password1,
      name: name,
    }); // Send as query paramers );
    // const loginresponse = await axios.post('/api/login', {email, password} )// Send as query paramers );
    // setIsloggedin(()=> true)
    router.replace("/dashboard");
    setLoading((loading) => !loading);
  } catch (error) {
    alert(error);
  }
};

The console.log doesnt work because im using nextjs with fast api backend. I just want to print the response from the create function to the front end so users know why the function error has occurred. At the moment the alert shows: AxiosError: Request failed with status code 403


Solution

  • See Axios - Handling Errors

    You can access the response body via error.response?.data.

    To display it in your Next.js component, you'd typically just use React state, for example

    const [error, setError] = useState<string>();
    
    const handlesignup = async (e: any) => {
      e.preventDefault();
      setError("");
      setLoading(true);
      try {
        const signupresponse = await axios.post("/api/signup", {
          email: signupemail,
          password1: password1,
          name: name,
        }); // Send as query paramers );
        // const loginresponse = await axios.post('/api/login', {email, password} )// Send as query paramers );
        // setIsloggedin(()=> true)
        router.replace("/dashboard");
      } catch (error) {
        console.warn('Signup failed', error);
        setError(error.response?.data ?? error.message);
      } finally {
        setLoading(false);
      }
    };
    
    if (error) {
      return <p className="error">{error}</p>;
    }